[英]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(). 对于两个摩天大楼使用相同的图案画布,将从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... 我当前的代码(也可以在下面的http://jsfiddle.net/zGsEh/7/中找到)是...
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/ 演示: 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.