下图即是在手机内置浏览器中打开的效果图,可以通过手指绘图,通过点击按钮清楚图画效果
js 代码
1 window.onload = function() { 2 3 document.ontouchmove = function(e){ e.preventDefault(); } 4 //禁用浏览器的滚动操作 5 6 var canvas = document.getElementById('main'); 7 var canvastop = canvas.offsetTop; 8 //canvastop 和窗体顶部的距离 9 10 var context = canvas.getContext("2d"); 11 //获得2D上下文 12 13 var lastx; 14 var lasty; 15 16 context.strokeStyle = "#000000"; 17 context.lineCap = 'round'; 18 context.lineJoin = 'round'; 19 context.lineWidth = 5; 20 21 //清空 22 function clear() { 23 context.fillStyle = "#ffffff"; 24 context.rect(0, 0, 300, 300); 25 context.fill(); 26 } 27 //画一个点 28 function dot(x,y) { 29 context.beginPath(); 30 context.fillStyle = "#000000"; 31 context.arc(x,y,1,0,Math.PI*2,true); 32 //中心点(x,y),半径(1),起始角度(0),结束角度(2*PI),方向逆时针(true) 33 context.fill(); 34 //填充 35 context.stroke(); 36 //绘制边界 37 context.closePath(); 38 //关闭路径 39 } 40 41 //画一线 42 function line(fromx,fromy, tox,toy) { 43 context.beginPath(); 44 context.moveTo(fromx, fromy); 45 //定义起始位置 46 context.lineTo(tox, toy); 47 //绘制起始位置之间 48 context.stroke(); 49 context.closePath(); 50 51 //线内没有区域,不需要fill()来填充 52 } 53 //开始划线 54 canvas.ontouchstart = function(event){ 55 //处理手指触摸屏幕响应 56 event.preventDefault(); 57 //禁用浏览器复制和粘贴操作 58 59 lastx = event.touches[0].clientX; 60 lasty = event.touches[0].clientY - canvastop; 61 //捕获触摸的位置 前面有 var canvastop = canvas.offsetTop 62 63 dot(lastx,lasty); 64 } 65 //连续移动划线 66 canvas.ontouchmove = function(event){ 67 event.preventDefault(); 68 69 var newx = event.touches[0].clientX; 70 var newy = event.touches[0].clientY - canvastop; 71 72 line(lastx,lasty, newx,newy); 73 74 lastx = newx; 75 lasty = newy; 76 } 77 78 79 var clearButton = document.getElementById('clear'); 80 clearButton.onclick = clear; 81 82 clear(); 83 }
html 代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta name="viewport" content="user-scalable=no,initial-scale=1.0,maximum-scale=1.0" /> 5 6 <style> 7 body { padding:10px; margin:0px; background-color: #ccc; } 8 #main { margin: 10px auto 0px auto; } 9 </style> 10 11 <script src="draw-tracer.js"></script> 12 </head> 13 <body> 14 <canvas id="main" width="300" height="300"></canvas> 15 </body> 16 </html>
可以发现javasript中仍然存在一些可以优化的函数