Add color to graphics using HTML Canvas

Alyssa Nicoll
InstructorAlyssa Nicoll
Share this video with your friends

Social Share Links

Send Tweet

Black is getting awfully boring, let’s add some color to our shapes.

We can use the fillStyle method on our context to add colors. In this lesson we will look at how we can pass color names, hex values, and rgba values as strings to fillStyle to add colors to our graphics.

We’ll also show why the order of where you call methods on context matters.

[00:01] We can add color to graphics that we've drawn in canvas by grabbing the context and setting the fillStyle equal to a string that is a color. You can use the default browser colors, like pink. If we refresh you'll see, oh, it's so beautiful. You could also say, of course, blue or whatever color you so desire.

[00:28] Another option is to use, instead of the variable of pink, you can say "I want to use RGB of 255192203." If we go over and refresh, we see that oh...oh my. This is because we need a string. Mm-hmm. Yep. Let's go back, refresh. Uh, gorgeous. Fillstyle always needs a string alongside RGB. In the same line of thought, you could also do RGBA. Beautiful.

[01:15] Finally, last, but not least for me would be the oh-so-wonderful hex value. Voilà. In order to give color to graphics you simply add fillStyle and set it equal to a string, mind you, of the color of your choosing in variable form, RGB, RGBA, or hex.

[01:47] Another important thing to note is the order. If you decided to use the fillStyle after you had drawn your rectangle, for instance, it would not work. Oh no. Do be sure to first grab the element from the dom, create the context, do all of your fancy things like give it a fillStyle, and then finally fill the rect or draw the rectangle.

[02:17] Bonus content. You can also, since we're not using this variable of canvas and this variable of context -- we're only using context in this situation -- you can go ahead and shorten these lines and just say, "Document, create selector, grab canvas," and then get the 2-D context off of that.

[02:38] Let's make sure and set this, though, to context because we're using that throughout the JavaScript. If we go back and refresh you'll see that our square is still there. We are golden, and everything's a little bit more cleaned-up. There you have it.