Rumah >hujung hadapan web >tutorial js >js通过canvas实现画笔功能手记
相信大家对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
请勿转载~~~~
Atas ialah kandungan terperinci js通过canvas实现画笔功能手记. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!