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

200
Vistas
FillRect() no funciona y los rectángulos no se dibujan

Quiero hacer 5 rectángulos en diferentes posiciones con un color específico. Pero no lo dibuja. aquí está mi código js:

 const xpos = [100, 200, 250, 200, 100]; const ypos = [500, 500, 550, 600, 600]; const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); for (i in xpos) { ctx.fillStyle = "red"; ctx.fillRect(xpos[i], ypos[i], 50, 50); }

código HTML :

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body id="body"> <canvas id="canvas" width="200px" height="200px" style="border: 2px solid black;"></canvas> </body> <script src="index.js"></script> </html>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Es fácil, tu lienzo es demasiado pequeño. No es posible dibujar un rectángulo en Y/X 500 cuando su lienzo tiene solo 200 px cuadrados. Intenté aumentar el tamaño del lienzo a 1000 px y funciona de maravilla. Así que cambia las coordinaciones o agranda el lienzo.

También realicé algunas mejoras en su código para evitar errores no deseados.

 const xpos = [100, 200, 250, 200, 100]; const ypos = [500, 500, 550, 600, 600]; const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); //Check if you always have a pair of coordinations, otherways you'll end up with an error if(xpos.length != ypos.length){ console.error("Number of X positions doesn't match the number of Y positions and vice versa.") }else{ for (var i=0;i<xpos.length;i++) { ctx.fillStyle = "red"; ctx.fillRect(xpos[i], ypos[i], 50, 50); } }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body id="body"> <canvas id="canvas" width="1000px" height="1000px" style="border: 2px solid black;"></canvas> </body> <script src="index.js"></script> </html>

Espero que esto ayude :)

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