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

Incorporating Canvas into a real page

From: HTML5: Graphics and Animation with Canvas

Video: Incorporating Canvas into a real page

In this example, we're going to see how to incorporate a canvas into a real web page. And to do that, we are going to use the Explore California example site that comes with your exercise files. So, here I've got the ExploreCalifornia exercise files ready to go. Let me first show you the page that we are going to build. So, if I bring up the index page, this is the Explore California web site that we've been working with. And I am going to click on the TOURS section, and you can see down here there is a list of tours.

Incorporating Canvas into a real page

In this example, we're going to see how to incorporate a canvas into a real web page. And to do that, we are going to use the Explore California example site that comes with your exercise files. So, here I've got the ExploreCalifornia exercise files ready to go. Let me first show you the page that we are going to build. So, if I bring up the index page, this is the Explore California web site that we've been working with. And I am going to click on the TOURS section, and you can see down here there is a list of tours.

What we are going to do is we are going to build a canvas-based tour finder, and here is what we are going to do. Let's go to the TOUR FINDER page. So, right now, you can see this example is empty, but let me show you the finished version so you can see what it is going to look like. Okay, it's going to look like this. So, we will have a canvas which displays a graph of some attributes of a given tour, and it will show us things like the duration, elevation, environment, and overall difficulty of a given tour.

So you see, as we choose different tours, the graph is changing to show us what the overall difficulty is. In this case, if it's easy, it turns green and if it happens to be a moderate tour, it turns yellow. And in the case of really difficult tours, you can see that the difficulty bar turns red. And you notice how as I am choosing each one of these tours, the graph is changing right here in the page. So, to do this without using canvas, you would have a couple of choices. You would either have to use some other dynamic media solution, such as a plug-in like either Silverlight or Flash, or you would have to build each one of these as a separate graphic image and then swap out the image whenever a new tour was chosen.

However, each time you added a new tour or if you changed some of the data associated with the particular tour, you would then have to either make a new image or go back and change the existing one, which is kind of labor intensive and is not really well suited to data intensive examples. Because again, let's suppose somebody goes and does some work on this particular tour and makes it easier. In the case of using the canvas, all you have to do is change one little data point and then the canvas graph is going to update automatically. To do this with an image or some other complex dynamic media solution, there would be a lot more work involved.

So, this is what we are going to build, so let's go build it. So, we are going to close this. Let's go to the code. So, here are the snippets for the Explore California example here in chapter 08. And I am going to go open up the starting point file, and here we are in ExploreCalifornia. So, open up the tourcompare page, and we're going to go ahead and scroll on down, and I'll show you where we are going to put this. So, we are going to put this right down here where it says tourDescriptions.

So, let's go back to our snippets and paste in the content we are going to need to let the user choose a tour, and that's down here. So, to do that, we are going to need this snippet of code, and I will paste it in and explain what it does. And we are going to put that right there. So, what I have done is I've pasted in some HTML code that has a select list in it, which is called tourSelector. And you can see that there's a series of options that allow me to choose the different tours. And then below that, I have my canvas, and you can see that my canvas has an id on it, and it's got a width and a height. And I put a little one- pixel solid border around it so we can see it in the page.

So just doing that, let me just save and let's go back to the browser and see how that looks. So, let's just go ahead and bring the tourcompare page up. And you can see that what I have done so far is here is the canvas and here is that select list. So, we are already pretty well on our way. All you do now is draw the canvas and then respond to changes in this menu such that when the menu changes, we redraw the canvas. So, let's go back and do that. Here we are back in the code. So, let's scroll up to the script portion, because that's where the rest of this is going to take place, and go back over to the snippets.

So, let's begin by copying the first few lines of code. And I will just copy this and explain it. And I'll put the closing script tag on there. So, what I have here is an array of tourdata, and inside that array, there is a series of objects, and there are five of them for the five tours. There is a few properties associated with each object. There is the tour name.

There is the tour duration. And I just chose these numbers arbitrarily on some scale, so these are just going to happen to work out to the size of the bars on the chart, but if you had some other prior existing data, you could put whatever you wanted in a chart like this and then just do whatever conversion you need to do to make the chart draw the right size bars. In this case, just to make the example simple, I have just got a 1:1 relationship between these numbers. So, for example, a duration of 200 means two days and so on and so forth. So, we have got duration.

You got values for elevation, value for how extreme the environment is, and then an overall difficulty rating. So, there is five objects, and then I have got a couple of variables here that are going to hold a reference to the tour canvas and the context for that canvas. So, let's go back to the snippets. Now, let's copy over the drawChart function. This is the function that's going to get called every time the select list index changes. So, this will take care of drawing the chart backgrounds, drawing the labels, and drawing the data.

So, let's copy over those. Let's copy over drawBackground first. So, I will copy this function over and we'll paste it. And for the time being, what we will do is we'll fill in little empty stubs for draw labels and draw tour data. So, we'll say function drawLabels (forWhichTour) and we will have a function drawTourData again (forWhichTour).

So, now we have those functions stubbed out and we can go ahead and take a look at the code. Actually, before we do that, let me do one more thing. Let's copy over the initialization code that sets up the chart when the page first loads, and that's this code right down here. So, here I'm using the jQuery code to create a function that runs when the page loads, and for the moment, let's go ahead and comment this one out.

What it's doing is it gets reference to the canvas, then gets the canvas's drawing context, and then it calls drawChart with 0 to initialize the chart to the first set of tour data. So, let's go ahead and save, and let's review this in the browser. Let's refresh. And you can see that right now we've got the canvas background drawing and the drawing area, so let's go to the code and see how that works. So, up here in the drawBackground, a couple of things happened. First, I save off the canvas context.

Again, I just do that because it's a nice practice in case any drawing came before this function got called. So, the first thing we do is fill in the chart background. So, we set the fillStyle to that brownish color, and then we call fillRect starting from the upper left and doing it for the entire width and height of the canvas. That's pretty simple. Then we create the graph area. So, we change the strokeStyle to a somewhat darkish gray color, and then we call strokeRect, and that's what gives us the outline of the area where we are going to draw the bars. Then we need to draw the chart lines. So, we change the strokeStyle to a slightly lighter gray color, and then we have a loop that starts at a certain point on the canvas, at the x point, goes to a certain x point, and increments every 20 pixels.

So, inside that loop, we begin a path, and then we just draw each line and stroke it, and that just creates that little bars across the drawing area, and then we are done. We restore the canvas context, and the function exits. So, now let's fill in the drawLabels function. The drawLabels function is responsible for two things: it draws the tour name and it draws the labels. So, let's copy that code and paste it in. So, again, we save and restore the context each time.

Again, that's a nice little practice-- not mandatory in this case, but we are doing it anyway. So, now we draw the tour name, so we set the font to be 24pt Arial, and we set the fillStyle to be the blue text color, and then we just call the fillText routine. FillText takes the constant string tour name plus the tour data's name property for whatever the currently selected tour is and draws that text at this location on the canvas, so that's that part. And for the labels, we change it to 20pt Arial and the fillStyle for that color, and then we draw the labels for duration, elevation, environment, and difficulty.

Again, we just use the fillText function at various points on the canvas. Let's save and let's refresh. So, we can see this being built up slowly over time. So, you can see that here's the labels that we drew on the canvas using the text function. Here's the tour name for the currently selected tour. And it starts out to 0, so that's the first data object. Now, what we need to do is draw the bars for the various data points and respond to changes in this menu. So, back in the code, let's go ahead and uncomment this function right here.

So, what we're doing is we are using jQuery to listen for the change event on the select list. Remember, we had the id of tourSelector. So, we are listening to the change event, and whenever the change event fires, we are simply calling a function that calls drawChart and we are getting the selectedIndex of the select list. So, this will go from 0 up to 4 because that's how many options there are in the select list. So, now that we've got that working, we can save.

And before we go ahead and draw the data, let's just go ahead and see the effects of that. So, we refresh and now you can see that as I change the menu, it's changing the currently selected tour, so the title is changing. All right, so now let's go back to the code, and now let's fill in the part where we actually draw the data and that's down here. So, what we are going to do is copy this, and we are going to paste it in to the drawTourData part.

So, let's go ahead and refresh the browser and see what the effects of this was. So, now we are getting the data drawn as well, and you can see that each time we are changing the selection, the data changes. So, let's go back to the code and explain what happened. As you may have guessed, drawing each one of those bars on the chart is just a rectangle. So to do that, recall that we set the strokeStyle and the fillStyle for the rectangle, and then it is just a matter of drawing each bar for the four properties. And remember, the forWhichTour index gets passed in from the function for drawing the chart, so we use that as an index into the tourData array.

So, we get each object and we just get the duration, elevation, environment, and then the difficulty for that particular tour. So, you can see that that's just a simple matter of calling fillRect and strokeRect for each one of those data points. At a particular point on the canvas starting here, they get this width. The value of that data field in that object just serves as the width, and each one of those bars is 30 pixels high. So, we fill each rectangle, and then we stroke it with a grayish color to give it an outline. So, we do that for each one of the data points.

Now, notice for the other properties, it's always yellow. But for difficulty, we are actually going to draw different colors based upon whether the tour is easy or hard or moderate. So, we've chosen a green color for easy yellow, yellow for moderate, and red for hard. So, that's just a simple matter of changing the fill style based upon what the difficulty rating is. So, we check the difficulty rating, and if it's less than or equal to 150, we choose the green color. If it's between 150 and 300, we choose the yellow color. And if the difficulty is more than 300, we choose the red color. And then we just fill and stroke the difficulty rect and draw it appropriately.

So, we save, refresh. And you can see now that as we choose each tour, we are getting a real-time chart drawn in the page. And let's just go ahead and try this in another browser. I am going to switch over to Firefox. Okay, here we are in Firefox. You can see, again, the same appearance, same behavior, right. So, we have built an interactive tour finder using canvas. So, let's just recap really quickly.

So, using the canvas, we built an area here in the page and we hooked up a select list whose change event we used to get the selected index to choose which tour data we are going to draw. We used rectangles, text, we used some paths in or to draw the canvas, and that's a real live example of incorporating campus into a real web page.

Show transcript

This video is part of

Image for HTML5: Graphics and Animation with Canvas
HTML5: Graphics and Animation with Canvas

37 video lessons · 18907 viewers

Joe Marini
Author

 
Expand all | Collapse all
  1. 4m 54s
    1. Welcome
      1m 3s
    2. Using the exercise files
      2m 3s
    3. Using the HTML5 Canvas element in the real world
      1m 48s
  2. 10m 31s
    1. Real-world example: CanvasMol
      2m 9s
    2. Real-world example: Raphaël-JavaScript Library
      1m 47s
    3. Real-world example: The Wilderness Downtown
      4m 1s
    4. Real-world example: Sketchpad
      1m 10s
    5. Real-world example: Pirates Love Daisies
      1m 24s
  3. 3m 28s
    1. Installing the tools
      1m 29s
    2. Exploring the Canvas examples used in this course
      1m 59s
  4. 8m 58s
    1. Introducing the Canvas tag
      6m 30s
    2. Understanding the differences between Canvas and SVG
      2m 28s
  5. 5m 36s
    1. Identifying the Canvas element's methods and properties
      1m 40s
    2. Using the Canvas drawing context
      3m 56s
  6. 43m 14s
    1. Setting and using colors and styles
      3m 19s
    2. Drawing basic shapes: Rectangles and lines
      10m 21s
    3. Understanding the Canvas state
      5m 15s
    4. Drawing complex shapes: Arcs and paths
      9m 15s
    5. Drawing complex shapes: Bézier and quadratic curves
      5m 46s
    6. Rendering text
      9m 18s
  7. 32m 35s
    1. Creating shadows
      6m 41s
    2. Drawing with patterns
      7m 20s
    3. Drawing with gradients
      6m 18s
    4. Using clipping paths
      4m 46s
    5. Drawing images and video
      7m 30s
  8. 35m 42s
    1. Transforming objects using the translate tag
      4m 18s
    2. Scaling objects with the scale transformation
      4m 7s
    3. Rotating objects with the rotate transformation
      4m 33s
    4. Applying a custom transformation
      6m 58s
    5. Compositing in Canvas using globalAlpha
      6m 36s
    6. Manipulating raw pixels
      9m 10s
  9. 41m 23s
    1. Building an image slideshow control
      4m 24s
    2. Using smooth transitions in a slideshow
      4m 28s
    3. Creating a basic animation
      5m 42s
    4. Creating animation with double buffering
      13m 13s
    5. Incorporating Canvas into a real page
      13m 36s
  10. 48s
    1. Goodbye
      48s

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.

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: Graphics and Animation with Canvas.

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.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

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.