javascript - 如何在 javascript/html 中制作 Canvas API 彩色图 block

标签 javascript canvas html5-canvas

我想让程序用随机颜色绘制矩形图案。我需要制作随机颜色,使用 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
}

然后布置图 block :

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 彩色图 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21619859/

相关文章:

canvas - 需要加速我的 SVG。我可以转换为 WebGL 或 Canvas 吗?

从按钮到函数的 JavaScript 事件

javascript - 尝试镜像 Canvas 上下文无法渲染 Canvas

android - Gridview,允许背景 Canvas 在 View 外绘制

html - 保存 html Canvas 图像

javascript - 绘制和删除圆弧 - 使用 JavaScript 或 CSS 的圆弧动画

javascript - Foundation 4 和 backbone.js 的等高柱

Javascript——按照指定的对象属性顺序对对象数组进行排序

javascript - 事件传播事件绑定(bind)

svg - 绘制 SVG 后的 Canvas 'tainted'