Reputation: 25
Using a single canvas, I have drawn five boxes, but when I fill them, only the final fillStyle is applied to all the boxes, despite the others having been assigned fillStyles.
e.g:
//Create AnswerBox 2
var context2 = document.getElementById("canvas").getContext("2d");
context2.rect(500, 410, 800, 100);
context2.fillStyle = "#bdff00";
context2.fill();
//Create AnswerBox 3
var context3 = document.getElementById("canvas").getContext("2d");
context3.rect(500, 520, 800, 100);
context3.fillStyle = "#f0ff00";
context3.fill();
//Create AnswerBox 4
var context4 = document.getElementById("canvas").getContext("2d");
context4.rect(500, 630, 800, 100);
context4.fillStyle = "#ff6600";
context4.fill();
//Create AnswerBox 5
var context5 = document.getElementById("canvas").getContext("2d");
context5.rect(500, 740, 800, 100);
context5.fillStyle = "#ec1a1a";
context5.fill();
Does this mean that a canvas can only draw with one fillStyle and I would need to use five smaller canvases to have five differently coloured boxes?
Upvotes: 2
Views: 3213
Reputation: 48297
Does this mean that a canvas can only draw with one fillStyle...???
nope, you can set/changr the fillStyle as much as you want/need, where the new value apply only to the object you draw at that point....
dont create context objets from the same canvas, reeuse it instead:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(20, 20, 150, 100);
ctx.fillStyle = "#00FF00";
ctx.fillRect(30, 30, 30, 30);
ctx.fillStyle = "#0000FF";
ctx.fillRect(70, 70, 30, 30);
the following code will produce multiple rects wit different styles:
Upvotes: 4