简体   繁体   中英

randomizing a canvas pattern to be a different color every time it is used in a .fillStyle in HTML5 Canvas

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM