相信大家對flash的畫線功能都並不陌生,我以前也用flash的actionscript寫過類似的功能,不過鑑於flash已經是被淘汰了的技術,
下面我們介紹如何透過html5的canvas標籤結合javascript實作畫板功能,
程式碼如下:
<script src="http://www.php.cn/static/home/js/jquery.min.js"></script> <canvas id="paintcanvas" width="600" height="700"></canvas> <script> var paint; var clickX=[]; var clickY=[]; var clickDrag=[]; function addClick(x,y,dragging) { clickX.push(x); clickY.push(y); clickDrag.push(dragging); } function redraw() { paintcanvas.strokeStyle = "#df4b26"; paintcanvas.lineJoin = "round"; paintcanvas.lineWidth = 5; for(var i=0; i < clickX.length; i++) { paintcanvas.beginPath(); if(clickDrag[i] && i){//当是拖动而且i!=0时,从上一个点开始画线。 paintcanvas.moveTo(clickX[i-1], clickY[i-1]); }else{ paintcanvas.moveTo(clickX[i]-1, clickY[i]); } paintcanvas.lineTo(clickX[i], clickY[i]); paintcanvas.closePath(); paintcanvas.stroke(); } } paintcanvas=$('#paintcanvas')[0].getContext("2d"); $('#paintcanvas').mousedown(function(e){ var mouseX=e.pageX-this.offsetLeft; var mouseY=e.pageY-this.offsetTop; paint=true; addClick(e.pageX-this.offsetLeft,e.pageY-this.offsetTop); redraw(); }); $('#paintcanvas').mousemove(function(e){ if(paint){ addClick(e.pageX-this.offsetLeft,e.pageY-this.offsetTop,true); redraw(); } }); $('#paintcanvas').mouseup(function(e){ paint = false; }); $('#paintcanvas').mouseleave(function(e){ paint = false; }); </script>
其中,透過mousedown, mousemove, mouseup, mouseleave等js事件實現畫線功能。
本文由php中文網提供,
原文網址:http://www.php.cn/js-tutorial-374130.html
請勿轉載~~ ~~
以上是js透過canvas實現畫筆功能手記的詳細內容。更多資訊請關注PHP中文網其他相關文章!