This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In


    Specifying Height and Width on the Canvas Element

    Alyssa NicollAlyssa Nicoll

    Let's take a look at a bug you can run across, by not specifying height and width of your HTML canvas element. We will look at giving the canvas element a height and width property inline. We’ll also look at how we can alternatively give canvas those height and width properties right in our Javascript.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    00:01 Right now, we have a canvas element that we're giving 500 by 500 within height. We're also calling out that canvas element, getting its 2D context, and, to that context, filling a rectangle that is the same width and height of the canvas element. Voila.

    00:23 However, what happens with this setup whenever we try to make it a size that's, I don't know, not the canvas size? Let's say 50 by 50. Remember here, you don't use units whenever you're specifying.

    00:38 Refresh. We get a not square looking shape. The reason this is happening is because our canvas element needs a set height and width. The one in the CSS will not do.

    00:53 If we give it a height of 500 and a width of, again the same, 500, we go back and refresh. We see that, voila, we are now getting a 50 by 50 square shape with our fillRect method.

    01:12 Another option instead of giving it inline is to go into the JavaScript and say canvas, our const up here that we just created, .width equals. Since I'm making mine a square, I can go ahead and set the height to the same thing. We'll say 500.

    01:33 If we go back over here, refresh. We'll see it doesn't break because this is also acceptable.