我正在尝试在 Canvas 中绘制矩形,用户单击该点并移动鼠标,将绘制矩形,完成后只剩下一个矩形,即最后一个。然而使用
let canvas = document.querySelector("canvas"), ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown",function(event){
x_ = event.pageX - this.offsetLeft;
y_ = event.pageY - this.offsetTop;
canvas.addEventListener("mousemove",function(event){
xmax = event.pageX - this.offsetLeft;
ymax = event.pageY - this.offsetTop;
console.log(x_,y_,xmax,ymax);
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.fillRect(0, 0, 10, 10);
ctx.rect(x_,y_,xmax-x_,ymax-y_);
ctx.stroke()
})
})
canvas {
border: 1px solid black;
}
<canvas></canvas>
clearRect
调用不起作用,因为之前的矩形仍然可见。
它没有理由不工作,为什么会这样?清除矩形后,将绘制新图像,并且所有先前的矩形都应该消失。
最佳答案
我看到您在最后调用了中风()
,这可能是问题所在。请查看此处的“使用说明”:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clearRect
A common problem with clearRect is that it may appear it does not work when not using paths properly. Don't forget to call beginPath() before starting to draw the new frame after calling clearRect.
关于javascript - clearRect 不清除 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49537546/