时间:2021-07-01 10:21:17 帮助过:27人阅读
下面我们介绍如何通过html5的canvas标签结合javascript实现画板功能,
代码如下:
<script src="http://www.gxlcms.com/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事件实现画线功能。
本文由Gxl网提供,
原文地址:http://www.gxlcms.com/js-tutorial-374130.html
请勿转载~~~~
以上就是js通过canvas实现画笔功能手记的详细内容,更多请关注Gxl网其它相关文章!