Jua*_*dán 29 javascript line onmousemove draw clear
我在body onmousemove函数上使用这个脚本:
function lineDraw() {
// Get the context and the canvas:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// Clear the last canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw the line:
context.moveTo(0, 0);
context.lineTo(event.clientX, event.clientY);
context.stroke();
}
Run Code Online (Sandbox Code Playgroud)
每次我移动鼠标时都应该清除画布,然后绘制一条新线,但它不能正常工作.我试图在不使用jQuery,鼠标监听器或类似工具的情况下解决它.
这是一个演示:https://jsfiddle.net/0y4wf31k/
avi*_*sim 63
你应该使用" beginPath() ".这就对了.
function lineDraw() {
var canvas=document.getElementById("myCanvas");
var context=canvas.getContext("2d");
context.clearRect(0, 0, context.width,context.height);
context.beginPath();//ADD THIS LINE!<<<<<<<<<<<<<
context.moveTo(0,0);
context.lineTo(event.clientX,event.clientY);
context.stroke();
}
Run Code Online (Sandbox Code Playgroud)
请注意,ctx.clearRect()在 Google Chrome 上无法正常工作。我花了几个小时试图解决一个相关问题,结果发现在 Chrome 上,它不是用 rgba(0, 0, 0, 0) 填充矩形,而是用rgba (0, 0, 0, 1) 填充矩形反而!
因此,为了用所需的透明黑色像素正确填充矩形,您需要在 Chrome 上执行以下操作:
ctx.fillStyle = "rgba(0, 0, 0, 0)";
ctx.fillRect(left, top, width, height);
Run Code Online (Sandbox Code Playgroud)
当然,这应该适用于为 HTML5 Canvas 对象提供适当支持的所有浏览器。