I believe everyone is familiar with the line drawing function of flash. I have written similar functions using flash's actionscript before. However, considering that flash is already an obsolete technology,
Below we introduce how to implement the drawing board function through the canvas tag of html5 combined with javascript. The
code is as follows:
<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>
Among them , the line drawing function is realized through mousedown, mousemove, mouseup, mouseleave and other js events.
This article is provided by php Chinese website,
Original address: http://www.php.cn/js-tutorial-374130.html
Please do not reprint~~ ~~
The above is the detailed content of js implements brush function notes through canvas. For more information, please follow other related articles on the PHP Chinese website!