Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda