canvas绘制自由线 完整代码 兼容移动端
完整的 canvas 绘制自由线的代码,兼容移动端操作如下:
<!DOCTYPE html> <html> <head> <title>Canvas 绘制自由线</title> <style> #canvas { border: 1px solid #ccc; } </style> </head> <body> <canvas id="canvas"></canvas> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var canDraw = false; // 是否能画图标志位 var lastPoint = null; // 上一次的鼠标位置 var isMobile = navigator.userAgent.toLowerCase().indexOf('mobile') !== -1; // 兼容 PC 和移动端的事件 canvas.addEventListener( isMobile ? 'touchstart' : 'mousedown', function (event) { event.preventDefault(); canDraw = true; lastPoint = isMobile ? { x: event.targetTouches[0].pageX, y: event.targetTouches[0].pageY, } : { x: event.offsetX, y: event.offsetY }; }, { passive: false } ); canvas.addEventListener( isMobile ? 'touchmove' : 'mousemove', function (event) { event.preventDefault(); if (!canDraw) return; var currentPoint = isMobile ? { x: event.targetTouches[0].pageX, y: event.targetTouches[0].pageY, } : { x: event.offsetX, y: event.offsetY }; // 绘制线条 context.beginPath(); context.lineWidth = 2; context.lineJoin = 'round'; context.lineCap = 'round'; context.moveTo(lastPoint.x, lastPoint.y); context.lineTo(currentPoint.x, currentPoint.y); context.stroke(); lastPoint = currentPoint; }, { passive: false } ); canvas.addEventListener( isMobile ? 'touchend' : 'mouseup', function (event) { event.preventDefault(); canDraw = false; lastPoint = null; }, { passive: false } ); </script> </body> </html>