我想要一个程序绘制带有随机颜色的矩形图案。我需要做随机颜色,使用JavaScript中的数学对象有一个随机数生成器。
该模式需要使用setInterval函数每隔几秒钟更改一次颜色。允许用户选择要包含在模式中的行数和列数。我不知道从哪里开始,除了:
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");发布于 2014-02-07 05:21:45
您只需根据行和列布局您的瓷砖,并为每个颜色组件生成一个带有Math.random()的颜色:
现场演示
例如,此函数将以字符串的形式返回一个随机颜色,您可以直接在fillStyle属性上设置该字符串。
function getRandomColor() {
return 'rgb(' + /// build string
((Math.random() * 255)|0) + ',' + /// R component
((Math.random() * 255)|0) + ',' + /// G component
((Math.random() * 255)|0) + ')'; /// B component
}然后把瓷砖铺好:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
rows = 10,
cols = 10,
cw = canvas.width / cols, /// get width of each cell
ch = canvas.height / rows; /// get height of each cell
function loop() {
/// loop through rows and columns
for(var y = 0; y < rows; y++) {
for(var x = 0; x < cols; x++) {
/// set random coloor
ctx.fillStyle = getRandomColor();
/// draw tile
ctx.fillRect(x * cw, y * ch, cw, ch);
}
}
}现在只需调用它一次来绘制,然后以毫秒为单位设置间隔:
loop();
setInterval(loop, 2000); /// update every 2 seconds提示:在使用beginPath()时,不需要使用fillRect(),因为这不会像rect()那样向路径添加任何内容。
希望这能有所帮助!
https://stackoverflow.com/questions/21619859
复制相似问题