Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

I'm making "my first HTML 5 game". Following the video perfectly but JavaScript won't create a rectangle in the canvas?

I'm making "my first HTML 5 game". Following the video perfectly but JavaScript won't create a rectangle in the canvas? Here's the code,

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

imgFrog = new Image();
imgFrog.src = "images/mikethefrog.png";
imgFrog.addEventListener("load",init, false);

var requestAnimFrame =
                window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                window.oRequestAnimationFrame ||
                window.msRequestAnimationFrame ||
                function (callback) {
                    window.setTimeout(callback, 1000/60);
                };

function init() {
    requestAnimFrame(update);
}

function update() {

    context.fillRect(  10, 10, 40, 380, "#000000");  


    requestAnimFrame(update);
}

1 Answer

Hey Isaac Oleksiuk,

The fillRect method only takes 4 parameters: x, y, width, height (respectively). You set the color with the fillStyle property like so:

//Either outside of the update() function like this:
context.fillStyle = "#000";
function update() {
    //Or you can do inside the update() function
    //It's up to you although it will be cached outside of the function
    //So that it doesn't get reset each time the function is called
    //context.fillStyle = "#000";
    context.fillRect(10, 10, 40, 380);  
    requestAnimFrame(update);
}