user37421
user37421

Reputation: 435

How to draw a huge number of dots (with regular pattern) on canvas?

The dots are arranged so they have a regular distance between them.

they are drawn at (x%4==0) and (y%4==0), they take time to be drawn in a brute force way:

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

how to do it in a better way?

dotted image

Upvotes: 0

Views: 1082

Answers (1)

user1693593
user1693593

Reputation:

You can use createPattern() by first creating an offscreen-canvas, draw a single dot into it, then use that canvas as a image source for createPattern(). Set pattern as fillStyle and fill.

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>

If this is not an option you can always optimize the code you have now by not filling each dot, but adding to the path and fill once:

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>

Upvotes: 2

Related Questions