New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

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

Creating animation with double buffering

From: HTML5: Graphics and Animation with Canvas

Video: Creating animation with double buffering

In this movie, we're going to see how to create a smooth animation using a technique known as double buffering. Double buffering is called that because all the drawing takes place on an offscreen canvas, or buffer, before it is copied to the onscreen canvas. The reason you do this is because if you have a lot of objects that are being animated, if you're just doing all the animation directly on the screen, the user might see things like flicker or other unwanted artifacts that don't happen when you draw everything offscreen first and then copy the finished frame onto the canvas.

Creating animation with double buffering

In this movie, we're going to see how to create a smooth animation using a technique known as double buffering. Double buffering is called that because all the drawing takes place on an offscreen canvas, or buffer, before it is copied to the onscreen canvas. The reason you do this is because if you have a lot of objects that are being animated, if you're just doing all the animation directly on the screen, the user might see things like flicker or other unwanted artifacts that don't happen when you draw everything offscreen first and then copy the finished frame onto the canvas.

So let's take a look at the example that we're going to build. I'm going to bring up my finished example, and you can see that what we have here is a nice nighttime sky with snowflakes of various sizes falling at various speeds and randomly drifting to the left at various rates. So this is the example that we're going to build. You can see that it's nice and smooth. There's no stuttering or anything like that. So this example is using double-buffering animation, so all the snowflakes are being animated on a canvas that you can't see off the screen, and then each frame, as it's completed, is copied onto the canvas.

So let's go ahead and build that. I'm going to open up my start point here in the editor and in the snippets and at my Double Buffer Animation, so let's copy things over. So this is just some initialization code. So here's the canvas and context that's in the page, and that's this canvas right here. But we also have variables for the buffercanvas, and this is a canvas that to we're going to create offscreen. We have an array to hold all the snowflakes, we have a timer that is used to animate each flake, and then we have a variable that keeps track of the maximum number of flakes we're going to have on the screen. So let's save.

Let's copy over the initialization function. So we copy that and we paste it. So the initialization function will get called when the document loads, and that's right here. So when the document loads, we're going to get a reference to the canvas in the context of the canvas that's in the page. And we're going to use that information to create a new buffer canvas. So you can see we're using the document's DOM right here to create a new canvas element, and then retrieve its context.

Now this canvas is not in the page; it's floating in space somewhere, but we can still use it to draw on. So once we've created the buffercanvas, we set its width and height to the same width and height of the canvas that's already in the page. Once we've initialized that, we set an interval timer that adds snowflakes to the scene over time. So every 200 milliseconds, or pretty much every fifth of a second, we'll be adding a new snowflake. Then we have a Draw function, which draws the initial setting, and then we have an animate timer which gets called every 30 milliseconds, or about every thirty-ish frames per second or so. So let's save.

Let's copy over the animation function, and the animation function is right here, paste. So the animation function follows a fairly standard pattern that you'll see throughout various animation techniques. Every time the animation function gets called which is about 30 times per second. The first thing it does is call Update function, then it calls Draw. Now Update is responsible for moving all of the animated objects on the screen.

So it's going to move each one of the snowflakes according to its speed and drift and so on. Once all the objects have been updated to their new locations, we then call the Draw function which updates the scene and copies the contents of the buffercanvas onto the onscreen canvas. So now that we have that in place, let's save, and let's copy over the supporting logic. So we have these two functions, addFlake and blank.

Let's copy that, and we'll put those in here. And let's copy over the Update and Draw functions as well, and we'll go through those and see what they do. So I'm going to put those guys down here. So as I mentioned earlier, we have Update and Draw, and now we copied over some supporting logic. The last thing we need to copy over is the logic that creates all the snowflakes.

So let's copy that over, and you can see that right here in addFlake, we have a call to a new Flake object. So I'm going to copy that because that's up here at the top, and we'll to paste that in. So here's how this works. So remember, we have a timer here that adds snowflakes to the screen gradually over time, and that's this function.

So we have an array; recall that we have an array of snowflakes. So each time this function gets called, we're going to create a new snowflake and put it in the array of snowflakes. And then once the length of the snowflake array has reached the maximum number of flakes we want, we then clear the snowflake timer so that no further flakes get added. So let's go back up and look at the initialization logic for each snowflake. So each snowflake on the screen is going to have some properties associated with it.

So each snowflake has an x and y position, and that's these two lines right here. So the snowflake is going to start out above the top of the canvas, so we initialize that to be -10 pixels so it appears off the canvas initially. Then we want to distribute each snowflake randomly along the X axis of the canvas so that it has a different starting position when it falls down. So we're going to use the built-in JavaScript's Math library to create a random number, and the random function gives us a random number between 0 and 1.

So we're going to multiply that by the width of the canvas. That will give us a random number that goes from zero up to the far right of the canvas, and then we'll just simply use the rounding function to round that to an n-digit number. So now we've initialized the x and y position of each snowflake, but we don't want each snowflake to just fall straight down--and that's kind of not very realistic. We want each snowflake to kind of drift a little bit. So we have a drift property, and again, we just have a little random number between 0 and 1, and we're going to add that to the x position each time to give it a little bit of a drift.

Then we have the speed at which each snowflake falls. So again, to be realistic, we want each snowflake to fall at a slightly different speed, so we have a random number between 0 and 1, times 5. That will give us a random number between 0 and 5. But we don't want zero because we don't want any snowflakes just sitting there out in space, not falling in defined gravity. So we add the number one to ensure that every snowflake at least has some speed, so this will now give us a random number between one and six.

Then we have to make the width and height of each snowflake. So we're going to give the width of the snowflake-- again, we want it to be realistic, and snowflakes are varying sizes-- so we'll have a random number between 0 and 1, times 3, so that'll give us a width between 0 and 3. But we can't have snowflakes of zero width, and we want to make sure that each snowflake is at least visible, so we'll add the number 2 to that. So now we have snowflakes of random width at least 2 and at most 5. And to make them square, we'll just set the height to be whatever the width is.

So now that we've created each snowflake, let's go back down and see what the Update function does. So remember, each time through the animate loop, we're going to update, then we're going to draw. So in the Update logic, for all of the snowflakes in the snowflake array, we need to update their position based upon their properties. So we check to see if this snowflake, if the y value is currently less than the height of the canvas; in other words, it still hasn't reached the bottom of the canvas yet. And if that's true, then we update the snowflake's position.

So we update its vertical position by adding the speed to whatever the y value is that will cause the snowflake to fall down a little bit more. If doing that has now caused the snowflake to fall off the bottom of the canvas-- in other words, the y value is now greater than the canvas height-- we reset the y value to be -5. That will reset it to be back up above the top of the canvas. So now we've updated the y position. Now we have to update the x position. Now remember, the x position gets updated because we don't want the snowflake to fall straight down; we want it to kind of drift a little bit randomly.

So each time through this animate loop, we're going to add the snowflake's drift amount to whatever its x position is. Then just like for the y position logic, we have to see if the x position is now greater than the canvas width, because it's drifted off the right side of the screen. If that's the case, we simply reset the x position of the snowflake to zero. So this is going to happen for all of the snowflakes in the array. So now when this function completes, all the snowflakes have been moved to their new position. So that means it's time for the Draw function to run.

So after Update, the Draw function is now responsible for drawing everything in its new location. So we have a save and a restore for the context--and these aren't mandatory, but it's a good practice to put them in. I just put them there in case any drawing comes before or after this particular function, if I have a complex animation that I'm working on. The first thing we do is call the blank function, and the blank function-- let's just scroll back up--all this does is draw our night sky. So we draw the background first with a nice deep purplish color, and we fill the rectangle on the buffercanvas, starting at the upper left down to the lower right.

And again, you can see that all the drawing is taking place on the offscreen buffercanvas, not on the onscreen one. So we just draw the background, and then we draw all the snowflakes. So once again, we have a loop that goes across the entire snowflake array, and for each one of the snowflakes, we set the fillStyle of the canvas on the buffercanvas to be white. And then again, on the buffercanvas, we just fill each rectangle represented by each snowflake.

So we have the x and y position and the width and the height of each snowflake. So we do that for all 200 flakes. Then when we've drawn everything to the buffercanvas, we copy the entire rendered image, this frame, from the buffercanvas onto the canvas that's on the screen. So we do that using the drawImage function that's on the onscreen canvas to copy the source, which is the buffercanvas. And again, we copy from the upper-left corner, all the way to the lower right.

So let's go ahead and save, and let's try it out. You can see now that we've got snowflakes beginning to fill the sky, and we've got a little drift going on, right? Some of them are drifting, some of them are falling at different a different speeds. So now let's get little bit fancy. Now let's add a clipping region, and remember, we learned about clipping regions earlier. So let's go back to the code. So what we're going to do now is scroll down here, and we're going to create a clipping region. I'm going to copy this and I'm going to paste it back in here.

So remember that clipping paths define an area outside of which drawing does not take place, and inside of which drawing shows through. So we're going to create a clipping region by calling the beginPath function, again, on the buffercanvas--all the drawing takes place in the buffercanvas. So we fill the entire buffercanvas with a black rectangle, starting at the upper left and going to the lower right. Then we draw an arc, and the arc is going to be drawn at the middle of the buffercanvas, so we divide the width by 2, the height by 2.

That gets at the center. We're going to give the arc a radius of 40% of whatever the canvas height is. So it's going to reach 40% in all directions. And since the radius is half the diameter, this will give us a circle of 80% of the canvas's height. And then finally we call clip which tells the canvas, only draw in the visible area which is represented by that circle. So let's save and let's see what this does. Let's refresh. Now we have a circle.

It's kind of like looking through a telescope, right? So now the snowflakes are only visible within the circular area. They're still being drawn out here. You just can't see it because the clipping region is precluding that from happening. But the effect that we've created is looking at a snowfall through say a telescope. That's our finished example. So in this movie, we've seen how to create smooth animation using a technique known as double buffering. And for good measure, we added a clipping region to clip the animation to a visible area, providing a nice nighttime snowfall effect.

Show transcript

This video is part of

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

37 video lessons · 18147 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

Are you sure you want to delete this note?

No

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.