我正在尝试使用html5 canvas和普通javascript创建一个简单的绘制/绘制程序.我的工作正常,但是当绘制和移动鼠标太快时,线路断开连接,我最终得到一条点线 – 我怎样才能使它成为一条平滑的连续线?
建议将不胜感激!我是JS的新手,所以代码示例非常有用,提前感谢.
目前的JS是:
var canvas,ctx var mouseX,mouseY,mouseDown = 0 function draw(ctx,x,y,size) { ctx.fillStyle = "#000000" ctx.beginPath() ctx.arc(x,size,Math.PI*2,true) ctx.closePath() ctx.fill() } function clearCanvas(canvas,ctx) { ctx.clearRect(0,canvas.width,canvas.height) } function onMouseDown() { mouseDown = 1 draw(ctx,mouseX,2) } function onMouseUp() { mouseDown = 0 } function onMouseMove(e) { getMousePos(e) if (mouseDown == 1) { draw(ctx,2) } } function getMousePos(e) { if (!e) var e = event if (e.offsetX) { mouseX = e.offsetX mouseY = e.offsetY } else if (e.layerX) { mouseX = e.layerX mouseY = e.layerY } } function init() { canvas = document.getElementById('sketchpad') ctx = canvas.getContext('2d') canvas.addEventListener('mousedown',onMouseDown,false) canvas.addEventListener('mousemove',onMouseMove,false) window.addEventListener('mouseup',onMouseUp,false) } init();
<canvas id="sketchpad" width="500" height="500"></canvas>
解决方法
您可以保存最后一个位置并在最后一个点和实际点之间画一条线.
if (lastX && lastY && (x !== lastX || y !== lastY)) { ctx.fillStyle = "#000000"; ctx.lineWidth = 2 * size; ctx.beginPath(); ctx.moveTo(lastX,lastY); ctx.lineTo(x,y); ctx.stroke(); // ... lastX = x; lastY = y; }
在mouseup事件中,将两个变量设置为零.
var canvas,mouseDown = 0,lastX,lastY; function draw(ctx,size) { if (lastX && lastY && (x !== lastX || y !== lastY)) { ctx.fillStyle = "#000000"; ctx.lineWidth = 2 * size; ctx.beginPath(); ctx.moveTo(lastX,lastY); ctx.lineTo(x,y); ctx.stroke(); } ctx.fillStyle = "#000000"; ctx.beginPath(); ctx.arc(x,true); ctx.closePath(); ctx.fill(); lastX = x; lastY = y; } function clearCanvas(canvas,2) } function onMouseUp() { mouseDown = 0; lastX = 0; lastY = 0; } function onMouseMove(e) { getMousePos(e) if (mouseDown == 1) { draw(ctx,false) } init();
<canvas id="sketchpad" width="600" height="300"></canvas>