我想让它在左下角

    1. const width = cvs.width
    2. ctx.fillStyle = 'red'
    3. ctx.fillRect(0, height - 10, 20, 10)

    画两个接起来,然后用变量来标识它们,然后找规律。

    多弄几个再找。

    1. w = 20
    2. h = 10
    3. ctx.fillStyle = 'red'
    4. ctx.fillRect(0, height - h, w, h)
    5. ctx.fillRect(0, height - 4 * h - 6, w, h)

    用循环写出来。

    1. let w = 20
    2. let h = 10
    3. let margin = 2 // 间隔
    4. let size = 4 // 方块数目
    5. ctx.fillStyle = 'red'
    6. for (let i = 0; i <= size; i++) {
    7. ctx.fillRect(0, height - (i + 1) * h - margin * i, w, h)
    8. }

    假设有一个 255 以内的随机数据,我们要映射到一个 20 的范围,获取百分比,乘以最大值即可。

    数据可视化(上) - 图1

    1. let maxSize = 20 // -> 255
    2. currentSize = Math.ceil((ramdom / 255) * maxSize)
    3. ctx.clearRect(0, 0, width, height)
    4. for (let i = 0; i <= currentSize; i++) {
    5. ctx.fillRect(0, height - (i + 1) * h - margin * i, w, h)
    6. }
    7. requestAnimationFrame(Run)
    8. }