繁体   English   中英

如何在javascript / html中制作canvas API彩色图块

[英]How to make a canvas API colored tiles in javascript/html

我想让一个程序绘制具有随机颜色的矩形图案。 我需要制作随机颜色,在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");

您只需根据行和列布置图块,并使用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

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

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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