简体   繁体   English

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

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

I want to have a program draw patterns of rectangles with random colors. 我想让一个程序绘制具有随机颜色的矩形图案。 I need to make random colors, using the Math object in JavaScript has a random number generator. 我需要制作随机颜色,在JavaScript中使用Math对象具有随机数生成器。

The pattern needs to change colors every few seconds using a setInterval function. 图案需要使用setInterval函数每隔几秒钟更改一次颜色。 Letting the user select the number of rows and columns to include in the pattern. 让用户选择要包含在模式中的行数和列数。 Don't know where to start except: 不知道从哪里开始,除了:

HTML HTML

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.
</canvas>

JavaScript: JavaScript的:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

You simply lay out your tiles based on rows and columns and generate a color with Math.random() for each color component: 您只需根据行和列布置图块,并使用Math.random()为每个颜色分量生成颜色:

Live demo 现场演示

For example, this function will return a random color as a string which you can set directly on the fillStyle property.: 例如,此函数将返回随机颜色作为字符串,您可以直接在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
}

Then lay out the tiles: 然后布置瓷砖:

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

Now just call it once to draw then set the interval in milliseconds: 现在只需调用一次即可绘制,然后以毫秒为单位设置间隔:

loop();
setInterval(loop, 2000); /// update every 2 seconds

Tip: There is no need for beginPath() when using fillRect() as this doesn't add anything to the path as for example rect() would. 提示:使用fillRect() beginPath()时不需要beginPath() ,因为这不会像rect()那样向路径添加任何内容。

Hope this helps! 希望这可以帮助!

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

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