Reputation: 87
I want to create multiple rectangles in my page, but I need to be able to edit their properties later on (color and position).
My html have:
<div id="display-area">
<canvas id="myCanvas">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
and my external 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);
}
}
I need to access these rectangles, but I'm only able to access the canvas. Is there any way or should I try a different implementation to have access to them?
Upvotes: 0
Views: 154
Reputation: 3974
In order to do this, you will need to keep track of all your rectangles, instead of just drawing random rectangles and then forgetting about them. Once the rectangles are drawn on the canvas, the canvas contains now knowledge of them anymore, only the pixels that resulted.
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);
}
Once you have a list of all the rectangles, any time you change one, you will need to re-render the canvas to update it.
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);
}
Upvotes: 2