在 Canvas 中,我绘制了两个矩形。在按钮点击事件中,我想从我绘制的这两个矩形中重绘一个矩形。我怎样才能做到这一点?
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.rect(10, 20, 150, 100);
ctx.fill();
ctx.rect(200, 20, 100, 100);
ctx.stroke();
change = () => {
//need to change height of second rectangle
alert('size changed')
}
在上面的 fiddle 链接中,我想更改第二个矩形的高度。任何人都可以提出实现这一目标的想法吗?
提前致谢
最佳答案
您需要重绘 Canvas - 即重绘背景和两个矩形,如下所示:
ctx.fillRect(0, 0, canvas.width, canvas.height);
//change the size of one rectangle, then redraw both of them
ctx.rect(10, 20, 150, 100);
ctx.fill();
ctx.rect(200, 20, 200, 150);
ctx.stroke();
另一种方法是只用白色矩形(或任何背景颜色)覆盖第二个矩形,然后重绘第二个矩形:
//draw first rectangle
ctx.rect(10, 20, 150, 100);
//cover old rectangle using a white rect
ctx.fillStyle = "white";
ctx.fill();
ctx.rect(200, 20, 100, 100);
//redraw second rectangle
ctx.fillStyle = "black";
ctx.fill();
ctx.rect(200, 20, 200, 150);
ctx.stroke();
关于javascript - 如何在 Canvas 中重绘矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55683637/