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>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 :)