gpt4 book ai didi

javascript - 如何在 javascript/html 中制作 Canvas API 彩色瓷砖

转载 作者:行者123 更新时间:2023-11-29 19:43:21 26 4
gpt4 key购买 nike

我想让一个程序用随机颜色绘制矩形图案。我需要制作随机颜色,使用 JavaScript 中的 Math 对象有一个随机数生成器。

图案需要使用 setInterval 函数每隔几秒改变一次颜色。让用户选择要包含在模式中的行数和列数。不知道从哪里开始,除了:

HTML

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

最佳答案

您只需根据行和列布置图 block ,然后使用 Math.random() 为每个颜色分量生成一种颜色:

Live demo

例如,此函数将以字符串的形式返回随机颜色,您可以直接在 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

提示:使用 fillRect() 时不需要 beginPath(),因为这不会向路径添加任何内容,例如 rect( ) 会。

希望这对您有所帮助!

关于javascript - 如何在 javascript/html 中制作 Canvas API 彩色瓷砖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21619859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com