Specifying Height and Width on the Canvas Element

Alyssa Nicoll
InstructorAlyssa Nicoll
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

[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.

Steven
Steven
~ 7 years ago

Why does the 50x50 square display properly in video 1 at 2:29, but not in this video at 0:40?

Markdown supported.
Become a member to join the discussionEnroll Today