alireza
alireza

Reputation: 25

FillRect() not working and rectangles doesnt be draw

I wanna make 5 rectangles in deiffrent positions with a specific color. But it doesn't draw it. here is my js code :

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);
}

html code :

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

Upvotes: 1

Views: 721

Answers (1)

aragocz
aragocz

Reputation: 51

It's easy, your canvas is too small. You can't possibly draw a rectangle on Y/X 500 when your canvas is only 200px square. I tried increasing the size of the canvas to 1000px and it works like a charm. So either change the coordinations, or make the canvas bigger.

Also i made some improvements to your code to prevent unwanted errors.

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>

Hope this helps :)

Upvotes: 3

Related Questions