- 实现思路
利用html5的canvas写字,思路就是记录鼠标移动过程中的点,然后用线连接起来就组成字.
- 具体实现
在鼠标按下时记录这个坐标,作为起始点,
鼠标移动时,从起始点开始把移动过程中的点用线连接起来.
鼠标松开时或者离开canvas时,停止连线.
- 涉及canvas技术
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d'); //获得canvas上下文
ctx.moveTo(moveX,moveY);//将moveX,moveY作为起始点
ctx.lineTo(evt.layerX,evt.layerY);//在当前坐标与evt.layerX,evt.layerY之间画线
- 完整代码
<html> <head> <title>canvas 写字</title> </head> <body> <div style="border:1px solid #FF0000; 800px;height:450px;" > <canvas id="myCanvas" width="800" height="450">你的浏览器不支持,请使用火狐\谷歌等浏览器</canvas> </div> 鼠标:<input type="text" id="show"/> <script> var canvas = document.getElementById("myCanvas"); canvas.addEventListener('mousemove', onMouseMove, false); canvas.addEventListener('mousedown', onMouseDown, false); canvas.addEventListener('mouseup', onMouseUp, false); canvas.addEventListener('mouseout',onMouseOut,false); var show=document.getElementById("show"); var ctx = canvas.getContext('2d'); //获得canvas上下文 var flag = 0; var isMoved=false; var moveX,moveY; function onMouseMove(evt) { if (flag == 1) { show.value="X:"+evt.layerX+" Y:"+evt.layerY; if(isMoved) { isMoved=false; ctx.moveTo(moveX,moveY); } ctx.lineTo(evt.layerX,evt.layerY); ctx.stroke(); } } function onMouseDown(evt) { flag = 1; isMoved=true; moveX=evt.layerX; moveY=evt.layerY; } function onMouseUp(evt) { flag = 0; } function onMouseOut(evt) { flag=0; } </script> </body> </html>