Reputation: 15673
Consider a simple canvas as
$(document).ready(function(){
draw();
});
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
}
How can I introduce variable into the jQuery function to draw several canvases with defined variable (e.g. color set).
In fact, I want to replace canvas id and its options (like color) with variable provided by draw(variables)
, e.g.draw(canvas_id, color, ...)
.
Example: (for creating several canvases on different DOM elements)
function draw(ccc) {
var canvas = document.getElementById(ccc);
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
}
draw(canvas1);
draw(canvas2);
Upvotes: 2
Views: 1473
Reputation: 8111
Here is one way you could do it:
function draw(colors) {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
for(var i=0; i < colors.length; i ++){
ctx.fillStyle = colors[i];
ctx.fillRect (10*i, 10*i, 55, 50);
}
}
}
// define some colors in an array
var colors = ["rgb(200,0,0)","rgba(0, 0, 200, 0.5)","rgba(0, 128, 200, 0.5)"];
draw(colors);
EDIT
Here is jsfiddle example
Upvotes: 1
Reputation: 144659
try this:
function draw(id, clr, fill) {
var canvas = document.getElementById(id);
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = clr;
ctx.fillRect (fill);
}
}
Upvotes: 1