javascript - 每次在 HTML5 Canvas 的 .fillStyle 中使用 Canvas 图案时,将其随机化为不同的颜色

标签 javascript html html5-canvas

使用两个 Canvas 。最初是为了 build 摩天大楼。第二,创建插入每座摩天大楼的模式。另外,我使用了随机颜色函数,以便每个建筑物都有新的颜色。

对两座摩天大楼使用相同的图案 Canvas 将从 randcolor() 发出相同的颜色。如何更改每个新元素的随机颜色,而不为每个图案创建新的 Canvas 元素?

我现在的代码,也可以在下面的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);

千言万谢

最佳答案

您可以设置一个函数,每次调用该函数时都会返回一个新模式:

演示:http://jsfiddle.net/m1erickson/zp3Ps/

enter image description here

返回新模式的示例代码:

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

用法:

ctx.fillStyle=newPattern();

关于javascript - 每次在 HTML5 Canvas 的 .fillStyle 中使用 Canvas 图案时,将其随机化为不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152565/

相关文章:

html - 在 HTML5 Canvas 中隐藏灰线

javascript - 为什么我不能获得超过 2 个变量来处理 HTML5 Canvas 和 JavaScript?

javascript - 将数组传递给 Google Chart

javascript - 每当文本字段动态为空时禁用按钮

javascript - 将 CSS 与 Express 结合使用

javascript - 如何将其自动化为 for 循环?

javascript - 将表单元格值用于 javascript 而不是 <td class>

调整大小的 HTML Canvas 最佳实践

javascript - 如何访问主体设置为原始数据的 postman 请求的 req.body.title

javascript - 解决猜词游戏中的 js 错误