Chooce video playback speed
speed:1

Specifying Height and Width on the Canvas Element

InstructorAlyssa Nicoll

Share this video with your friends

Send Tweet

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.

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.

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.

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.

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.

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.

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