Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Drawing in the canvas environment

From: HTML5 First Look

Video: Drawing in the canvas environment

Now that our Canvas element is on the page and we're importing content into it, we'll experiment with drawing in our Canvas by plotting a line to show elevation data. Drawing in the Canvas environment is pretty simple, but there are a huge variety of drawing methods that can assist you in drawing and styling artwork within Canvas. It's worth noting that the only methods available for drawing shapes are methods for drawing rectangles. To draw other types of shapes, you'll need to either combine or close paths that you've drawn by using other methods. Let's take a look at a few of the drawing methods in the Canvas API by plotting our graph on top of the map.

Drawing in the canvas environment

Now that our Canvas element is on the page and we're importing content into it, we'll experiment with drawing in our Canvas by plotting a line to show elevation data. Drawing in the Canvas environment is pretty simple, but there are a huge variety of drawing methods that can assist you in drawing and styling artwork within Canvas. It's worth noting that the only methods available for drawing shapes are methods for drawing rectangles. To draw other types of shapes, you'll need to either combine or close paths that you've drawn by using other methods. Let's take a look at a few of the drawing methods in the Canvas API by plotting our graph on top of the map.

Okay, so I have the trails.htm from the 06_03 folder open, and we're just going to draw this inside the onload function we have for the image, because we don't want to try to draw on to the map until the map is finished loading. So, what I'm going to do is directly after the line, where we're drawing the image, I'm just going to keep adding to my script here. The first thing I need to do to draw any type of a shape other than a rectangle or a path is to use the beginPath method. So, I'm going to type in the elvPlot, elevation plot, .beginPath.

So, that tells the Canvas API that we want a new shape or a new stroke. I'm going to go down to the next line, and I'm going to use the moveTo method. So, I'm going to type in elvPlot.moveTo, and I need to pass two coordinates into the moveTo method, and I'm going to do 89, 644. So, let's talk about that for just a moment. All right, the moveTo method doesn't actually draw anything. The easiest way to visualize what moveTo is doing is imagine that you have a pen and you're picking it up and you're moving it around a piece of paper.

Wherever you set your pen down and you begin drawing, that's where you've moved to. So, really that's what moveTo is going. We're basically saying we want to start drawing this path or this shape at these coordinates. Now, as you can imagined, I've already plotted the points out where I need this path to be drawn. I've done that within Illustrator, but you can do it by simply drawing any type of a graph, and figuring out where the X and Y coordinates need to be for this particular shape. So, we're moving it 89 pixels over to the right, 644 pixels down. That's where we're going to start our graph. So, now I'm going to go down to the next line and here I'm going to type in elvPlot, and we're going to use a different method to actually draw the line.

Here we're going to use the lineTo method, lineTo. Go ahead and open up a pair of parenthesis and lineTo also needs X and Y coordinates to be passed into it. So, here we're going to do 106, 627. So, again, really what we're doing here is we're saying okay, move the pin to this location and then draw a line to these coordinates, and here we're doing 106 and 627. Let's save our file. Now, obviously we haven't drawn the entire graph yet, but we can visualize this if you'd like.

I'm going to go down to the next line and here I'm going to type in elvPlot.stroke. So, stroke is a method much like drawImage. drawImage draws the image into the Canvas environment. Stroke says, okay, all the stuff above this where I'm drawing a path, go ahead and draw that. Now, there are different methods to draw as well. Stroke concentrates on drawing paths and lines, as you can imagine. So, I'm going to save this, test this in a browser that supports Canvas, and if I scroll down, we can see the first part of our graph being plotted.

So, here's the moveTo, here's lineTo, and it strokes in between that. Perfect! Okay now, I want to use a little bit of digital wizardry here. It's kind of the nice thing about being able to record the titles this way and have them edited. I'm going to switch back into my code, and just like magic, my graph is finished now. The reason I'm doing this is because I would imagine it would be extremely boring to sit here and watch me do a line after line after line. So, what you can do now is you can just pause your video, leave these up on the screen, and go ahead and pass in all of these coordinates.

Just remember the first coordinate is the x-coordinate; the second coordinate is the y-coordinate. So, for each one of these, it's going to draw a line from this position to this position, and then draw another line from this position to this position. So, that's exactly what we're doing here and the very end of this stroke is going ahead and drawing that path. So, go ahead and pause the video and then plot the rest of your points. I'll wait here for you. Okay, cool! So, good job! So, let's save this and we'll go ahead and preview this as well, and now when we scroll down, we can see the remainder of our graph is plotted out.

That's amazingly simple, isn't it? I mean that looks really-- Well, okay, so it doesn't look that good, but at least the graph is finished. Now, we need to sort of address the fact that it really doesn't look that good. You'll notice that we're getting default styling. We have a very thin line. It's black. The lines are being joined using a miter join. That may or may not be what we want. So, let's talk about some methods that are going to allow us to style these lines, the way that we want them to look. All right, so we're back in our code, and now that we've got this graph plotted out, we need to go ahead and style this. Now, setting styles using Canvas is kind of interesting, because essentially you just set styles in your code and then anything that comes after those styles will use those styling attributes.

That means that every time you start a new path, you also need to pass in new styling information. So, what we're going to do is just above the beginPath, I'm going to go ahead and use some methods to style our line. So, again here, I'm going to type in elvPlot.lineWidth. So, if you want to change the size of your stroke, you're going to use lineWidth. I'm going to set that value equal to 4. Now, my recommendation is that you use even numbers. Canvas elements are drawn with a centerline stroke. What that means is half the stroke is on one side of the line, the other half is on the other.

If you use an odd number, you're basically getting sort of a fractional split on both sides, but if you're use an even number, we'll have two pixels to the right and two pixels to the left of line and it will give you a much nice, smoother, crisper line. So, we're going to use 4 there. The next thing I'm going to do is go down to the next line and I'm going to do elevation plot. Helps if I type that correctly. Now, you'll notice Dreamweaver is doing a really nice thing here for me. It's remembering the methods I've used before, which is nice. The next thing I'm going to do here is lineJoin, lineJoin, and I'm going to set that value equal to round.

So, I'm going to do a round join instead of a miter join. You've got three possible values here. You can do round, bevel, and miter. Miter is the default, which gives you those really sharp edges. Round, of course, is going to give you a rounded edge. And bevel will sort of flatten the edge of the line where it joins. Then finally we're going to give it a color, so I'm going to go down to the next line and again here do elevation plot .strokeSyle. So, there is a fillStyle method, and there is a strokeStyle method. The strokeStyle method, I'm going to pass into this a hexadecimal value for color and I'm just going to do 7f7f7f.

It's a gray color that we've been using throughout the site. So, it will help keep the look of these lines consistent with the rest of the site. So, 7f7f7f, perfect! You could also pass in RGB values, and if it's supported in the browser, you could also use RGB alpha values. If you've ever done that with CSS3 styles, it will work here as well. So, again I'm going to save this and test it. Scroll down and check it out. Yeah, now my line is being styled the way that I want it to. I'm getting those nice sort of smooth, rounded edges to it. It's the gray color and the line is much thicker, so we can see it a little bit better.

Because we used an even thickness, it's a good bit crisper. Now, the last thing that we need to do here is we need to draw sort of the black stroke that serves as sort of an outline for this portion of the graph. Now, you may have wondered, well, why didn't you just put that in Illustrator, because isn't every map going to have that? It is, but if I did that, this graph would be drawn on top of it and you would actually see this sort of edge here. We want to cover that up. So, we're going to do that by drawing another path on top of it and it's very, very quick and painless to do that. So, we'll go back into our code and do that really quickly.

All right, so anytime you want a path after you've finished drawing one, you need to use the beginPath method again. So, right after where I'm invoking the stroke method, I'm just going to come in and say elvPlot.beginPath. So, again, I'm just telling it hey, I want to go ahead to start drawing a new shape or a new path. Here again I need to pick up the pen or the cursor if you will, and move it to a new location to start drawing. So, I'm going to type in elvPlot. moveTo, and again I need to pass some parameters into moveTo, and this is going to 89, 434.

Below that, we just need to draw this and this one is pretty quick. So, I'll go ahead and let you watch me do the whole thing here. So, elvPlot.lineTo. Here, we're going to pass some coordinates in. We're going to pass 89, 645. So it's a straight line. It's using the same x-coordinate. We go down the next line and type in elvPlot.lineTo, and inside that I'm going to type in 567, 645. Again, this is another straight line, because this time it's using the same y-coordinate.

Finally, remember in order to draw it, we need to use the stroke method. So, elvPlot.stroke. That should draw our line for us. Let's go ahead and save and test that. If I scroll down, indeed we do see that line on top of it. Now, you'll notice that this line is using the exact same styling properties of our last one. It's got this rounded corner to it. It's 4 pixels wide, which is maybe what we want, and it's the same gray color. Well, we want it to stand out a little bit more and rather this one have sort of a sharp edge to it. So, we need to go ahead and change those.

Let's go back in our code and remember what I said earlier. Any of these style attributes that's set to your shapes are going to apply to anything below it. So, we essentially just need to go ahead and interrupt that process and put new ones in there, and I'm going to do that right above the beginPath. So, again, I'm going to type in elvPlot.lineJoin. I'm going to reset that to miter. So, even though miter is the default, this one was using round because of the previous lineJoin property. So, I'm going to go down to the next line and type in elvPlot and here I'm going to use the lineWidth one more time, and I'm going to give that a value equal to 4.

Now, I know it's the same exact value and you're probably like, well, why would you do that? Well, within any type of an application, you might want to know exactly what value you're using. If you have to keep going back up through the code to find out what that value is, it could cause a little bit of problems. So, putting this right above the beginPath is my way of just basically saying that hey, these are the styling parameters for this particular line. So, it's a little bit more code, but it helps me find it a little faster. Then finally, I need to change the color of this, so I'll type in elvPlot.strokeStyle, and here I'm going to set the value equal to, and in quotation marks, #333.

So, that's sort of a dark gray there. We're going to save that and test it. Cool! Now we get exactly what we were looking for. We have that sort of dark gray line on top of it. Notice that it's covering up the beginning of that graph, which is perfect, and now our graph is using that sort of softer, rounder style, instead of that one. Okay, so that's a quick example of Canvas and some of the drawing methods available to you inside Canvas. For more information on Canvas, I really encourage you to go to the WHATWG or the W3C's site, and read up on the specification for yourself.

I also recommend checking out the demos and guidelines I mentioned earlier in the chapter. One thing I want to talk very briefly about before we close is detection. Even though we've provided fallback content for unsupported devices, I think you'll agree with me that the fallback option is pretty weak. So, there are a lot of ways to check for Canvas support. I mean you could do a conditional statement and check to see if Canvas and the context is supported, and then write that Canvas element to the page, but I recommend using the Modernizr library. It's available here at modernizr.com. It's a very, very simple download. It's got full documentation.

Notice here you can see it in action. Modernizr is checking my current browser and letting me know which properties it supports. So, it's really cool. It's just a one-click download and the documentation on the site here is very, very good about how to use it. So, go ahead and check out the site, download the library, read through the documentation on how to detect for specific features. It's quick. It's easy. It helps you support Canvas now, if you want to use Canvas inside your documents now, by providing you a little bit of a more robust fallback method for the devices and browsers that might not support it.

Show transcript

This video is part of

Image for HTML5 First Look
HTML5 First Look

50 video lessons · 74418 viewers

James Williamson
Author

 
Expand all | Collapse all
  1. 3m 56s
    1. Welcome
      1m 1s
    2. Using the exercise files
      1m 50s
    3. Who is this course for?
      1m 5s
  2. 21m 12s
    1. Exploring prior standards
      4m 26s
    2. Why do we need HTML5?
      3m 32s
    3. HTML5 timeline
      4m 24s
    4. Current HTML5 support
      4m 25s
    5. What HTML5 is (and what it isn't)
      4m 25s
  3. 27m 49s
    1. HTML5 vs. HTML4
      3m 25s
    2. New structural tags
      6m 1s
    3. New content tags
      4m 7s
    4. New application-focused tags
      5m 32s
    5. Deprecated elements
      4m 28s
    6. API overview
      4m 16s
  4. 22m 29s
    1. Content models
      5m 33s
    2. Understanding the outline algorithm
      3m 21s
    3. The role of ‹div› tags
      4m 20s
    4. Using ID and class attributes
      2m 6s
    5. DOCTYPE declarations
      4m 16s
    6. Character encoding
      2m 53s
  5. 41m 27s
    1. Basic page structure
      3m 40s
    2. Structuring top-level elements
      7m 30s
    3. Structuring interior content
      8m 42s
    4. Building headers
      9m 11s
    5. Checking document outlines
      5m 46s
    6. Ensuring cross-browser structure
      6m 38s
  6. 27m 53s
    1. New input types
      5m 57s
    2. Setting form autofocus
      2m 53s
    3. Using placeholder data
      4m 4s
    4. Marking required fields
      3m 24s
    5. Working with number inputs
      5m 49s
    6. Using date pickers
      5m 46s
  7. 1h 1m
    1. Canvas overview
      6m 21s
    2. Adding canvas content
      8m 58s
    3. Drawing in the canvas environment
      12m 9s
    4. Drag-and-drop API overview
      6m 18s
    5. Offline applications overview
      7m 11s
    6. Video overview
      5m 45s
    7. Encoding video
      8m 23s
    8. Adding video
      5m 58s
  8. 57m 33s
    1. Geolocation API overview
      5m 50s
    2. Web storage API overview
      5m 40s
    3. WebSockets overview
      4m 16s
    4. CSS3 overview
      6m 38s
    5. Enhancing typography with CSS3
      7m 42s
    6. Using @font-face
      7m 11s
    7. Styling HTML5 with CSS3
      10m 23s
    8. Using CSS3 transitions
      9m 53s
  9. 5m 6s
    1. Final thoughts
      3m 49s
    2. Goodbye
      1m 17s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed HTML5 First Look.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.