Draw in HTML Canvas

Alyssa Nicoll
InstructorAlyssa Nicoll
Share this video with your friends

Social Share Links

Send Tweet

It’s really fun to work with graphics when building apps and websites, but how do you get started? HTML5 has a technology called Canvas that lets us draw graphics to our screens. We can do everything from making basic shapes to creating complex interactive games and animations!

In this course, we will learn the basics of using Canvas. We’ll start by learning how to create a canvas on an HTML page. Next we will learn how to draw and style with fills and strokes. Finally, we will add interactivity to canvas elements.

[00:00] We'll start off by creating a canvas element, and we'll give it a super semantic and helpful ID called canvas. We'll head on over to our style.css file. There, we're going to call out our canvas element. We're going to give it a width of, let's say, 200 pixels and a height of 100 pixels -- rectangle shape.

[00:29] Now, we'll head on to the final file for script.js. Inside of our self-invoking function, we're going to do three simple lines of JavaScript. First, we're going to create a variable called -- you guessed it -- canvas. We're going to go ahead and use document. querySelector. That's going to grab the element with the ID of canvas.

[01:06] The canvas variable will then allow us to get the context. We'll say const context=we'll use our canvas variable, and we'll say get context, and inside that pass it to D. From here on out, we won't use our canvas variable. That was just to grab the context. From here on out, drawing, animating, what have you, we'll use context.

[01:32] Let's draw a simple rectangle shape. We'll of course use the context. We'll say context. fillRect, for rectangle. This will take four parameters, an X, a Y -- I want to start at the top left -- and then a width, and a height. Nifty trick you can do is say canvas width and canvas height.

[01:58] Now, we'll see that we have a black rectangle that is filling up the exact width and height we gave our canvas in the CSS. If I go back to the CSS and I change that to, say, 400, you'll see that the rectangle [inaudible] really, really long. We'll change this back to 200.

[02:16] If we wanted to, we could give it a custom width and height. It doesn't have to match its parent canvas. We could say 50, 50. You'll see now that it is a square. Woo-hoo-hoo. Super exciting.

[02:30] A quick note, if you made your width and height larger than the canvas bounds you gave, all you would see is a black rectangle that was 200 by 100. This is because any shape that's larger than your canvas just gets cut off. Our rectangle is 50,000 by 5,000, but it's being cut off by the canvas bounds.