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.
I love your explanations, very fun to watch. please make more videos!
@Kunle
there is still the "canvas"-ID in the html, so everything is fine. :) She just got rid of the js variable. and if you mean the info to "canvas.width": the context still knows what "canvas" is, just console.log(context);
In Lesson 2, at the end when you shortened the code where you remove canvas variable to just grab the context, it has a bug, you are still referencing canvas when you get the height and width, but there is no canvas variable.
I am asking the same question.
haha, fun to watch!
In Lesson 2, at the end when you shortened the code where you remove canvas variable to just grab the context, it has a bug, you are still referencing canvas when you get the height and width, but there is no canvas variable.