Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Both squares aren't showing up on the canvas

This is my code:

const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");

function draw() {      
        context.fillStyle = "rgb(200, 0, 0)";
        context.fillRect(50, 50, 0, 0);
};

draw();

When I run it, I get no errors but it doesn’t add the squares to the canvas. Can someone tell me why this happens and how to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One problem you have is that your second Rect does not have a height and width.
the function has the parameters x, y, width, height -> fillRect(x, y, width, height). So you line context.fillRect(50, 50, 0, 0); creates a box with width and height of 0 at 50px from x and y.

const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
const settings = {x: 50, y: 50, height: 50, width: 50};

function draw() {
        if (ctx) {
                ctx.fillStyle = "rgb(0, 200, 0)";
                ctx.fillRect(settings.x, settings.y, settings.width, settings.height);
                
                ctx.fillStyle = "rgb(200, 0, 0)";
                ctx.fillRect(0, 0, 50, 50);
        };
};

draw();
<canvas id="myCanvas"></canvas>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading