简体   繁体   中英

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.

The pattern needs to change colors every few seconds using a setInterval function. Letting the user select the number of rows and columns to include in the pattern. Don't know where to start except:

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

You simply lay out your tiles based on rows and columns and generate a color with Math.random() for each color component:

Live demo

For example, this function will return a random color as a string which you can set directly on the fillStyle property.:

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.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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