Ok, let's get started here.
Here we have a skeleton html file. Write or copy the following into your text editor of choice:
Ok, so you don't need to add the part about me being amazingly cool. Add whatever you like there.
Say, Ben, what is Canvas anyway?
Well, it's an element used for displaying all kinds of neat stuff that was never before possible to display with previous versions of HTML. To have your mind blown, check this out:
Pretty neat, huh? This stuff can be done in HTML5 thanks to the good old Canvas element. Can't do THAT in Flash! Bet you're itchin' to start making this stuff yourself! Speaking of Flash, if you come from a Flash background, you'll notice that the graphics API has a lot of things in common with what I'm going to be showing you over the next couple lessons. But it's also a heck of a lot different...frustratingly so at times! Arghh!
Let's do this step by step:
And there you have it! You should see NOTHING except the text written in the title tag. But you'll start seeing stuff soon enough.
So now that you're all caught up, let's dive in and start messing with the canvas.
First off, let's return to our skeleton HTML file from before:
So wait a second...why don't we see the canvas when we run this little bit of code? Well, that's because the default color of the canvas is white. To change that, why don't we add some CSS to the code like this:
...and you'll see a nice dark grey background in the 550 X 400 space occupied by the <canvas>. Try any color you like. Just don't get too carried away, wiseguy!
So now we're going to learn two VEEERY important lines of code:
Now with the first of these beautiful lines of code, you're accessing the <canvas> HTML tag which we ID'd as "canvas". With the second, we're determining the context which our canvas will use. In our case we'll be using "2d". The other option is "webgl", but don't use it since this is for 3d stuff and isn't fully supported as of yet. That is, unless you're reading this in the future! Deeeep!
Remember that whatever you name the variable on the second line, you will write OVER and OVER again, especially when drawing lines and stuff, so don't go crazy can call it something like "theContextOfMyHTMLFileHeyWhatABeautifulDayItIsToday" because it's going to slow ya down. And in this fast-paced life, we can't afford to be slowed down!
So these two lines set up your canvas for you. Now let's try to add something to it just for fun!
Directly underneath the two lines you just wrote, add the following:
...then run it and tweet me what you see at @benwhi
So that's it for part one - I hope you'll follow along as we dig into the basic functions of the canvas API with shapes, lines, arcs and other neat stuff.
Thanks for following along! Code didn't work for you? Hate me? Are you my illegitimate child? Send input anytime!
Back to The Lessons Index
Onward to Lesson Two!