Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Split canvas into 100 pieces in Javascript

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();
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!