Search code examples
javascriptcanvasgraphics

How do I fill only the bottom third of a canvas with color using the y-axis in Javascript?


I'm a beginner coder in high school using CodeHS to learn. Sorry if the answer to this question is really simple, I'm just starting.

One of my assignments asks me to "draw" the Netherlands flag. That means the canvas will be split up into thirds. The top third has to be red, the middle should be left blank and the bottom third must be blue.

Here's what I have so far:

function start(){
    redRect();
    blueRect();
}

function redRect(){
    var x = getWidth();
    var y = getHeight() / 3;
    var rect = new Rectangle(x, y)
    rect.setColor("red");
    add(rect);
}

function blueRect(){
    var x = getWidth();
    var y = getHeight() - 2/3;   <-------- This is where I'm stuck
    var rect = new Rectangle(x, y)
    rect.setColor("blue");
    add(rect);
}

I thought that by filling the entire canvas using getHeight(), then subtracting 2/3 of the filled canvas would only fill the bottom third of the canvas with blue, thereby completing the flag. Instead, when I run the program, the blue fills the entire canvas.

How do I fill only the bottom third of the canvas with blue? Should I just create the rectangle first, then move it down?

Thank you so much! Have a great day!


Solution

  • Looking at the documentation

    This should do it

    function start(){
        var width = getWidth() 
        var height = getHeight()
        redRect(width, height);
        blueRect(width, height);
    }
    
    function redRect(width, height){
        var rect = new Rectangle(width, height/3)
        rect.setColor("red");
        add(rect);
    }
    
    function blueRect(width, height){
        var rect = new Rectangle(width, height/3)
        rect.setColor("blue");
        rect.move(0, height*2/3)
        add(rect);
    }