在画布上,我绘制了两个矩形。在按钮单击事件中,我想从我绘制的这两个矩形中重画一个矩形。我该如何实现?
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')
}
在上面的小提琴链接中,我想更改第二个矩形的高度。谁能提出实现此目标的想法?
预先感谢
答案 0 :(得分:2)
您需要重绘画布-即重绘背景和两个矩形,如下所示:
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();
答案 1 :(得分:1)
您需要保存矩形信息,并在每次更改时重新绘制它们。
这是因为画布不会将信息存储为对象,而只会提交像素。
//Setup canvas
var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext('2d');
canvas.height = 200;
canvas.width = 400;
ctx.fillStyle = "red";
//Setup rectangles as objects
var rect1 = { x: 10, y: 20, w: 150, h: 100 };
var rect2 = { x: 200, y: 20, w: 100, h: 100 };
//Setup controls
var table = document.body.appendChild(document.createElement("table"));
var tr = table.appendChild(document.createElement("tr"));
tr.appendChild(document.createElement("td")).innerHTML = "X-position:";
var xInput = tr.appendChild(document.createElement("input"));
xInput.type = "number";
xInput.value = rect2.x.toString();
tr = table.appendChild(document.createElement("tr"));
tr.appendChild(document.createElement("td")).innerHTML = "Y-position:";
var yInput = tr.appendChild(document.createElement("input"));
yInput.type = "number";
yInput.value = rect2.y.toString();
tr = table.appendChild(document.createElement("tr"));
tr.appendChild(document.createElement("td")).innerHTML = "Width:";
var wInput = tr.appendChild(document.createElement("input"));
wInput.type = "number";
wInput.value = rect2.w.toString();
tr = table.appendChild(document.createElement("tr"));
tr.appendChild(document.createElement("td")).innerHTML = "Height:";
var hInput = tr.appendChild(document.createElement("input"));
hInput.type = "number";
hInput.value = rect2.h.toString();
//Draw function
function change() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
[rect1, rect2].forEach(function (rect) {
ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
});
}
//initial draw
change();
//Redraw event
function redraw() {
rect2.x = parseInt(xInput.value, 10);
rect2.y = parseInt(yInput.value, 10);
rect2.w = parseInt(wInput.value, 10);
rect2.h = parseInt(hInput.value, 10);
change();
}
//Bind events
[xInput, yInput, wInput, hInput].forEach(function (input) {
input.addEventListener("change", redraw);
input.addEventListener("keyup", redraw);
});