我想在我的页面中创建多个矩形,但我需要能够稍后编辑它们的属性(颜色和位置)。
我的HTML有:
<div id="display-area">
<canvas id="myCanvas">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
和我的外部javascript:
function drawRectangles() {
var i;
var x = 0;
var y = 0;
/* Set the size of canvas */
document.getElementById('myCanvas').setAttribute('width', '600');
document.getElementById('myCanvas').setAttribute('height', '500');
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "rgb(0,0,0)";
/* Creates 50 rectangles in random positions and colors */
for (i = 0; i < 50; i++) {
x = Math.floor((Math.random() * 550) + 1);
y = Math.floor((Math.random() * 450) + 1);
context.fillStyle = getRandomColor();
context.strokeRect(x, y, 50, 50);
context.fillRect(x, y, 50, 50);
}
}
我需要访问这些矩形,但我只能访问画布。有没有办法或者我应该尝试不同的实现来访问它们?
答案 0 :(得分:2)
为了做到这一点,你需要跟踪所有的矩形,而不是仅仅绘制随机矩形,然后忘记它们。一旦在画布上绘制了矩形,画布就会立即包含它们的知识,只包含产生的像素。
var rectangleList = [];
/* Creates 50 rectangles in random positions and colors */
for (i = 0; i < 50; i++) {
x = Math.floor((Math.random() * 550) + 1);
y = Math.floor((Math.random() * 450) + 1);
var color = getRandomColor();
// Save the rectangle in a list for later.
rectangleList.push({
x: x,
y: y,
color: color,
});
context.fillStyle = color;
context.strokeRect(x, y, 50, 50);
context.fillRect(x, y, 50, 50);
}
获得所有矩形的列表后,无论何时更改一个矩形,都需要重新渲染画布以进行更新。
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "rgb(0,0,0)";
for (i = 0; i < rectangleList.length; i++) {
// Iterate through each of the previously remembered rectangles, then re-draw them.
x = rectangleList[i].x;
y = rectangleList[i].y;
var color = rectangleList[i].color;
context.fillStyle = color;
context.strokeRect(x, y, 50, 50);
context.fillRect(x, y, 50, 50);
}