簡體   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