Reputation: 1659
Using two canvases. The original to make the skyscrapers. The second, to create the pattern to insert into every individual skyscraper. In addition, I am using a random color function, so that each building has a new color.
Using the same pattern canvas for both skyscrapers will emit the same color from the randcolor(). How do I change the random color for each new element, without creating a new canvas element for each pattern?
My current code, which can also be found in the following http://jsfiddle.net/zGsEh/7/ is...
var c = document.getElementById('canvas1');
var ctx = c.getContext('2d');
//create and setup new canvas to be used for pattern
var pattern = document.createElement('canvas');
pattern.width = 2;
pattern.height = 10;
var pctx = pattern.getContext('2d');
pctx.fillStyle = 'hsl(' + 360 * Math.random() + ', 50%, 50%)';
pctx.fillRect(0,0,12,14);
pctx.lineWidth = 1;
pctx.strokeStyle = 'rgb(255,255,255)';
pctx.strokeRect(0,0,22,22);
//set up variable for
var pat1 = ctx.createPattern(pattern, 'repeat');
//building 1
ctx.fillStyle = pat1;
ctx.fillRect(0, 260 , 100,240);
//building 2
ctx.fillStyle = pat1;
ctx.fillRect(100, 210, 100, 290);
ctx.fillRect(115, 500-340, 70, 50);
ctx.fillRect(130, 100, 40, 60);
ctx.fillRect(140, 40, 20, 60);
A thousand thank you's
Upvotes: 0
Views: 338
Reputation: 105015
You can set up a function that returns a new pattern with each call to that function:
A Demo: http://jsfiddle.net/m1erickson/zp3Ps/
Example code to return a new pattern:
function newPattern(){
pctx.clearRect(0,0,pattern.width,pattern.height);
//setup up design for pattern
pctx.fillStyle = randomColor();
pctx.fillRect(0,0,12,14);
pctx.lineWidth = 1;
pctx.strokeStyle = 'rgb(255,255,255)';
pctx.strokeRect(0,0,22,22);
return(ctx.createPattern(pattern,'repeat'));
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
Usage:
ctx.fillStyle=newPattern();
Upvotes: 1