javascript - 如何在 Canvas 上绘制大量点(具有规则图案)?

标签 javascript algorithm canvas graphics

点的排列使它们之间有规则的距离。

它们是在 (x%4==0) 和 (y%4==0) 绘制的,它们需要时间以暴力方式绘制:

for (var x = 0; x < width; x+=4) {
    for (var y = 0; y < height; y+=4) {
        draw(x, y, 1, 1);
    }
}

如何以更好的方式做到这一点?

dotted image

最佳答案

您可以使用 createPattern()首先创建一个离屏 Canvas ,在其中画一个点,然后将该 Canvas 用作 createPattern() 的图像源。将图案设置为 fillStyle 并填充。

var ctx = c.getContext("2d");
var pattern = ctx.createPattern(createPatternImage(), "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, c.width, c.height);

function createPatternImage() {
  var ctx = document.createElement("canvas").getContext("2d");
  ctx.canvas.width = ctx.canvas.height = 4;   // = size of pattern base
  ctx.fillStyle = "#fff";
  ctx.fillRect(0,0,1,1);
  return ctx.canvas;                          // canvas can be used as image source
}
<canvas id=c style="background:#c00"></canvas>

如果这不是一个选项,您始终可以通过不填充每个点来优化您现在拥有的代码,而是添加到路径并填充一次:

var ctx = c.getContext("2d");   // obtain only one time.
var width = c.width, height = c.height;

ctx.beginPath();                // clear path if it has been used previously
ctx.fillStyle = "#fff";          

for (var x = 0; x < width; x+=4) {
    for (var y = 0; y < height; y+=4) {
        draw(x, y, 1, 1);
    }
}

// modify method to add to path instead
function draw(x,y,width,height) {
  ctx.rect(x,y,width,height);
}

// when done, fill once
ctx.fill();
<canvas id=c style="background:#c00"></canvas>

关于javascript - 如何在 Canvas 上绘制大量点(具有规则图案)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464360/

相关文章:

Javascript - 插入不包含框的复制文本

algorithm - 你如何使用 Dijkstra 找到更多的路线?

algorithm - 结合 semacodes 和隐写术?

javascript - 使用背景图片移动 HTML5 Canvas

javascript - 从 NG 绑定(bind)结果访问单个对象

javascript - 函数外的数组分配了空间,但函数外的变量在javascript中没有分配空间,为什么?

python - 煎饼排序中最短翻转序列的计数

javascript - 画圆线然后擦掉

javascript - 使用 fabric.js 的镜像克隆对象位置问题

javascript - JS/jQuery : Reverse animate triggered by hover?