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

194
Views
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 answers
Answer question

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 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!