Home > Mobile >  Split canvas into 100 pieces in Javascript
Split canvas into 100 pieces in Javascript

Time:01-26

So, I want to split canvas into 100 squares 50x50px and I want to do it with as little code as possible. I started making it with for loops but I would then need 10 for loops. I want to know is there a faster way with one for loop or so photo

and here is the code

let canvas = document.querySelector("canvas");
canvas.width = 500;
canvas.height = 500;
let c = canvas.getContext("2d");

let x = 0;
let y = 0;
for(let i = 0; i < 10; i  )
{
    if (i==0)
    {
        c.beginPath();
        c.moveTo(0, 50);
        c.lineTo(50, 50);
        c.lineTo(50, 0);
        c.stroke();
    }
    x  = 50;
    c.beginPath();
    c.moveTo(x, 50);
    c.lineTo(x   50, 50);
    c.lineTo(x   50, 0);
    c.stroke();
}
x = 0;
y = 0;
for(let i = 0; i < 10; i  )
{
    if (i==0)
    {
        c.beginPath();
        c.moveTo(0, 100);
        c.lineTo(50, 100);
        c.lineTo(50, 50);
        c.stroke();
    }
    x  = 50;
    c.beginPath();
    c.moveTo(x, 100);
    c.lineTo(x   50, 100);
    c.lineTo(x   50, 0);
    c.stroke();
}

CodePudding user response:

Put the drawing part in a function, and loop once, like this:

let canvas = document.querySelector("canvas");
canvas.width = 501;
canvas.height = 501;
let c = canvas.getContext("2d");

function draw(X, Y, x, y) {
  c.beginPath();
  c.moveTo(X, Y);
  c.lineTo(x, y);
  c.stroke();
}
for (let n = 0.5; n < 501; n  = 50) {
  draw(n, 0, n, 500);
  draw(0, n, 500.5, n);
}
<canvas></canvas>

Notice, that I've started the loop from 0.5, this "centers" the lines to the canvas pixels making the grid sharper.

  •  Tags:  
  • Related