We launched a new IT training category! Check out the 140+ courses now.

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

Adding canvas content

From: HTML5 First Look

Video: Adding canvas content

In the previous movie, we discussed the Canvas element and its related 2D API. In this movie, we will apply what we've learned to our trail guide page by adding Canvas content to the page to replace our trail guide map. Currently, the page's map and elevation guide on the page is a single image. We are going to replace that with Canvas element that's going to allow us to pull in our map as a separate image and then draw the elevation guide through the Canvas API. To illustrate that, I've got our map opened here in Illustrator, which was the program I used to create it.

Adding canvas content

In the previous movie, we discussed the Canvas element and its related 2D API. In this movie, we will apply what we've learned to our trail guide page by adding Canvas content to the page to replace our trail guide map. Currently, the page's map and elevation guide on the page is a single image. We are going to replace that with Canvas element that's going to allow us to pull in our map as a separate image and then draw the elevation guide through the Canvas API. To illustrate that, I've got our map opened here in Illustrator, which was the program I used to create it.

So this is the current map graphic as you see it on the page. So let's say our site has 50 different trails that we need to represent. That would mean that we would need to create a trailed map for every single one of those guys. So a new topographical map, a new pass for the trail itself, plot all the trailheads on it, and then do the trail elevation graph itself. Well, Canvas can make those types of chores a little bit easier. So what we're going to do is we're going to remove the trail elevation plot guides from our map, and then we're going to draw those using Canvas.

So we're going to import this graphic into our Canvas element and then draw on top of it using the Canvas API. Now, this has a lot of potential uses. Imagine, for example, that you could take all of your trails and put them in a database. You could place the trail guide elevation plot points in a database, you could place the topographical maps in a database, you could do the background image in a database, and you can go ahead and plot drawing the trail maps as well in a database. You can assemble them all at runtime based on which trail you were looking at and have the Canvas API draw all those elements together in a composition.

That would make life a little bit easier on you. Now, rather than doing something quite that complex for our example, what we're going to do is sort of just a piece of it. We are going to take this part of the map, which has been exported out as a JPEG, and then we're going to draw on top of it to add these plot points by using the Canvas API. So you should still be able to get a really good feel for how you might accomplish a composition of this nature. Now that we sort of understand what we're going to be doing with our trail guide map, let's switch back over to our HTML page and begin coding it. Okay, so here I am in the trails.htm file.

I've opened this up from the 06_02 directory and currently, we don't have a Canvas element on our page. We just have an image tag that's showing a mockup of what it's eventually going to look like. So I am going to scroll down in my code to find that image, which is found on Line 66 for me right here. There is our Canvas_mockup. So I am just going to go ahead and delete that image tag, and I want to go ahead and add a tag. So I am going to type in canvas, and I need to add some attributes to this. The first attribute I need to add would be an ID.

So the ID for this is going to be myMap. That's how we are going to reference this object through our script to let it know which canvas we want to draw into. The next thing we need to do is establish a width and a height. So I am going to give this a width of 600 and then give it a height of 695. So I will go ahead and close the opening tag and then close the tag itself. Now, we could just go ahead and leave it as this, but it's a really nice idea to provide some fallback content. So inside the tag, I am just going to type in "Your browser does not support Canvas.

Please upgrade to the latest version of Chrome, Firefox, or Safari." So really kind of weak fallback content there, but at least it would display and let somebody know that hey, you are missing out on something. Okay, so we've created our Canvas element, we've given it a name, we've given it a width and a height. So really, the only thing that Canvas element does is it informs the browser that hey, we need a drawing environment, we want it to be placed here within our page, and we want it to be this size.

What you place in the drawing environment is totally up to the Canvas API, and we need to go ahead and take care of that part next. So I am going to scroll up into the head of my document and just above the conditional comments for Internet Explorer, but just below the link to my style sheet, I am going to add a script tag and so I am just going to throw in a script tag here. Type is going to be text JavaScript. Now, you'd probably want to externalize these scripts on your own, but for the purpose of this exercise, we will just go ahead and embed them in the head of our document, and the first thing that I need to do here is to create a function to draw my map.

So I am just going to type in function drawMap and open and close some curly braces. This is a habit I have gotten into over the years because I have a really bad habit of forgetting those closing curly braces, especially if I am working with larger functions. So I always create sort of a skeleton before I do anything else. The next thing we need to do is go ahead and create an object for our map. So I am just going to type in var elvPlot for elevation plot. Next thing, you need to reference the Canvas element on the page that I am going to be drawing into using this object.

So I am going to type in =document. getElementById and remember we named the Canvas element myMap. So I am going to use myMap for that, and then I need to pass in which API we're going to be drawing with. So I am going to do getContext and I am going to pass into that 2d. Now that tells it that I am going to be using the 2D drawing API. So all my methods and properties are going to be coming from that particular API. Remember, the 3D API hasn't even really been formalized yet, but that is something that you need to do so it understands which methods and which specification you're working with.

So I am going to go down to the next line and now we need to worry about the external image that we're going to be loading into our map. The first thing I am going to do to handle that is to create an object to store our image. So I am going to type in var img = newImage and then I need to go out and tell it which image to load into that object. So I am going to do img.src = and here I am just going to give it a path directly to the image. So _images/northridge_map.jpg.

Now, this could be a dynamic link to your image, but in this case we're just pointing it to that specific graphic to tell it that that's the one that we want. Okay, so now that we've created an object to store our image and loaded the image inside of it, we are ready to draw that into our Canvas environment. We do that through the use of the drawImage method. Now, it's really tempting to just go ahead and call the drawImage method and call it a day, but there's a little bit of a problem with that. This script is going to execute very quickly, faster for the most part than your image can load from its server.

So, it's a really good idea to not call the drawImage method until the image has finished loading. We're going to do that by using an onload event handler to call the drawImage method. I'll do that just above where I've declared the source of the image. So what I am going to do here is I am going to type in img.onload = function and then inside the onload event handler here, I am going to type in elvPlot.drawImage. Now, the drawImage method needs three properties passed into it.

The first thing it wants to know is hey, which image am I drawing to the Canvas environment? And that's going to be the img image, and then the next thing it wants to know is what's my X coordinate and what's my Y coordinate, or where should I be placed? So I am going to type in ,0,0. So that's going to position it at the X coordinate of 0, and the Y coordinate of 0. So the top left-hand corner of the image will be aligned with the top left-hand corner of the Canvas itself. Since the Canvas element is the same size as the image, it should be a nice, snug fit.

So I am going to save this and we're almost ready to test it, but as of yet, we have not called the drawMap function. Now, you could trigger that function any way you wanted to. So really that's based upon the application or how you are applying the Canvas element on the page. We are just going to do it through very simple means. I am going to go down to the tag and I am going to trigger it by using an onload event handler on the body. So, a little primitive, but for this exercise it works just fine. So I am going to type in onload= and inside of that, I am going to type in drawMap.

So I am going to go ahead and call that function. All right! I am going to go ahead and save the file and now I am going to go ahead and test this in any browser that supports the Canvas element. In this case, I am going to do Chrome and as I scroll down, cool,. Now I get to see the image. So the image is there, but unlike last time when we were just using the image tag, notice that this version of it does not have those plot points. So we've created a Canvas element on the page, we've written a script that references that element, it's loading an external image and then it draws that image to the Canvas. Well, now that we have that image on our Canvas, we could, if we wanted to, scale it, transform it, tile it or further modify it using any of those methods and properties in the Canvas API, but that's not what we want to do.

We want to draw that graph. So in our next movie, we're going to experiment with drawing in the Canvas element by plotting our elevation graph.

Show transcript

This video is part of

Image for HTML5 First Look
HTML5 First Look

50 video lessons · 75012 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 preferences from 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.