You are previewing HTML5 Canvas.

HTML5 Canvas

Cover of HTML5 Canvas by Steve Fulton... Published by O'Reilly Media, Inc.
  1. HTML5 Canvas
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Preface
      1. Running the Examples in the Book
      2. What You Need to Know
      3. How This Book Is Organized
      4. Conventions Used in This Book
      5. Using Code Examples
      6. We’d Like to Hear from You
      7. Safari® Books Online
      8. Acknowledgments
    4. 1. Introduction to HTML5 Canvas
      1. The Basic HTML Page
      2. Basic HTML We Will Use in This Book
      3. The Document Object Model (DOM) and Canvas
      4. JavaScript and Canvas
      5. HTML5 Canvas “Hello World!”
      6. Debugging with Console.log
      7. The 2D Context and the Current State
      8. The HTML5 Canvas Object
      9. Another Example: Guess The Letter
      10. What’s Next
    5. 2. Drawing on the Canvas
      1. The Basic File Setup for This Chapter
      2. The Basic Rectangle Shape
      3. The Canvas State
      4. Using Paths to Create Lines
      5. Advanced Path Methods
      6. Compositing on the Canvas
      7. Simple Canvas Transformations
      8. Filling Objects with Colors and Gradients
      9. Filling Shapes with Patterns
      10. Creating Shadows on Canvas Shapes
      11. What’s Next
    6. 3. The HTML5 Canvas Text API
      1. Displaying Basic Text
      2. Setting the Text Font
      3. Text and the Canvas Context
      4. Text with Gradients and Patterns
      5. Width, Height, Scale, and toDataURL() Revisited
      6. Final Version of Text Arranger
      7. What’s Next
    7. 4. Images on the Canvas
      1. The Basic File Setup for This Chapter
      2. Image Basics
      3. Simple Cell-Based Sprite Animation
      4. Advanced Cell-Based Animation
      5. Applying Rotation Transformations to an Image
      6. Creating a Grid of Tiles
      7. Zooming and Panning an Image
      8. Pixel Manipulation
      9. Copying from One Canvas to Another
      10. What’s Next
    8. 5. Math, Physics, and Animation
      1. Moving in a Straight Line
      2. Bouncing Off Walls
      3. Curve and Circular Movement
      4. Simple Gravity, Elasticity, and Friction
      5. Easing
      6. What’s Next?
    9. 6. Mixing HTML5 Video and Canvas
      1. HTML5 Video Support
      2. Converting Video Formats
      3. Basic HTML5 Video Implementation
      4. Preloading Video in JavaScript
      5. Video and the Canvas
      6. Video on the Canvas Examples
      7. Animation Revisited: Moving Videos
      8. What’s Next?
    10. 7. Working with Audio
      1. The Basic <audio> Tag
      2. Audio Formats
      3. Audio Tag Properties, Functions, and Events
      4. Playing a Sound with No Audio Tag
      5. Creating a Canvas Audio Player
      6. Case Study in Audio: Space Raiders Game
      7. What’s Next
    11. 8. Canvas Game Essentials
      1. Why Games in HTML5?
      2. Our Basic Game HTML5 File
      3. Our Game’s Design
      4. Game Graphics: Drawing with Paths
      5. Animating on the Canvas
      6. Applying Transformations to Game Graphics
      7. Game Graphic Transformations
      8. Game Object Physics and Animation
      9. A Basic Game Framework
      10. Putting It All Together
      11. The player Object
      12. Geo Blaster Game Algorithms
      13. The Geo Blaster Basic Full Source
      14. Rock Object Prototype
      15. What’s Next
    12. 9. Combining Bitmaps and Sound
      1. Geo Blaster Extended
      2. Creating a Dynamic Tile Sheet at Runtime
      3. A Simple Tile-Based Game
      4. What’s Next
    13. 10. Mobilizing Games with PhoneGap
      1. Going Mobile!
      2. Creating the iOS Application with PhoneGap
      3. Beyond the Canvas
      4. What’s Next
    14. 11. Further Explorations
      1. 3D with WebGL
      2. Multiplayer Applications with ElectroServer 5
      3. Conclusion
    15. Index
    16. About the Authors
    17. Colophon
    18. SPECIAL OFFER: Upgrade this ebook with O’Reilly
O'Reilly logo

Advanced Path Methods

Let’s take a deeper look at some of the other methods we can use to draw paths on the canvas, including arcs and curves that can be combined to create complex images.


There are four functions we can use to draw arcs and curves onto the canvas. An arc can be a complete circle or any part of a circle


context.arc(x, y, radius, startAngle, endAngle, anticlockwise)

The x and y values define the center of our circle, and the radius will be the radius of the circle upon which our arc will be drawn. startAngle and endAngle are in radians, not degrees. anticlockwise is a true or false value that defines the direction of the arc.

For example, if we want to draw a circle with a center point at position 100,100 and with a radius of 20, as shown in Figure 2-4, we could use the code below for the contents of drawScreen():

context.arc(100, 100, 20, (Math.PI/180)*0, (Math.PI/180)*360, false);

Example 2-4 illustrates the code necessary to create a simple circle.

Example 2-4. A circle arc

function drawScreen() {

      context.strokeStyle = "black";
      context.lineWidth = 5;
      context.arc(100, 100, 20, (Math.PI/180)*0, (Math.PI/180)*360, false);

      //full circle

A basic circle arc

Figure 2-4. A basic circle arc

Notice that we have to convert our start angle (0) and our end angle (360) into radians by multiplying them by (Math.PI/180). By using 0 as the start angle and 360 as the end, we create a full circle.

We can also draw a segment of a circle by not specifying the entire 0 to 360 start and stop angles. This code for drawScreen() will create one-quarter of a circle drawn clockwise, as shown in Figure 2-5:

context.arc(100, 200, 20, (Math.PI/180)*0, (Math.PI/180)*90, false);
A one-quarter circle arc

Figure 2-5. A one-quarter circle arc

If we want to draw everything but the 0–90 angle, as shown in Figure 2-6, we can employ the anticlockwise argument and set it to true:

context.arc(100, 200, 20, (Math.PI/180)*0, (Math.PI/180)*90, true);
A three-fourths circle arc

Figure 2-6. A three-fourths circle arc


context.arcTo(x1, y1, x2, y2, radius)

The arcTo method has only been implemented in the latest browsers—perhaps because its capabilities can be replicated by the arc() function. It takes in a point (x1,y1) and draws a straight line from the current path position to this new position. Then it draws an arc from that point to the y1,y2 point using the given radius.

The context.arcTo method will work only if the current path has at least one subpath. So, let’s start with a line from position 0,0 to position 100,200. Then we will build our small arc. It will look a little like a bent wire coat hanger (for lack of a better description), as shown in Figure 2-7:

context.lineTo(100, 200);
An arcTo() example

Figure 2-7. An arcTo() example

Bezier Curves

Bezier curves, which are far more flexible than arcs, come in both the cubic and quadratic types:

The Bezier curve is defined in 2D space by a “start point,” an “end point,” and one or two “control” points, which determine how the curve will be constructed on the canvas. A normal cubic Bezier curve uses two points, while a quadric version uses a single point.

The quadratic version, shown in Figure 2-8, is the simplest, only needing the end point (last) and a single point in space to use as a control point (first):

A simple quadratic Bezier curve

Figure 2-8. A simple quadratic Bezier curve

This curve starts at 0,0 and ends at 0,50. The point in space we use to create our arc is 100,25. This point is roughly the center of the arc vertically. The 100 value for the single control point pulls the arc out to make an elongated curve.

The cubic Bezier curve offers more options because we have two control points to work with. The result is that curves—such as the classic “S” curve shown in Figure 2-9—are easier to make:

A Bezier curve with two control points

Figure 2-9. A Bezier curve with two control points

The Canvas Clipping Region

Combining the save() and restore() functions with the Canvas clip region limits the drawing area for a path and its subpaths. We do this by first setting rect() to a rectangle that encompasses the region we would like to draw in, and then calling the clip() function. This will set the clip region to be the rectangle we defined with the rect() method call. Now, no matter what we draw onto the current context, it will only display the portion that is in this region. Think of this as a sort of mask that you can use for your drawing operations. Example 2-5 shows how this works, producing the clipped result shown in Figure 2-10.

Example 2-5. The Canvas clipping region

function drawScreen() {

      //draw a big box on the screen
      context.fillStyle = "black";
      context.fillRect(10, 10, 200, 200);;

      //clip the canvas to a 50×50 square starting at 0,0
      context.rect(0, 0, 50, 50);

      //red circle
      context.strokeStyle = "red"; //need list of available colors
      context.lineWidth = 5;
      context.arc(100, 100, 100, (Math.PI/180)*0, (Math.PI/180)*360, false);
      //full circle


      //reclip to the entire canvas
      context.rect(0, 0, 500, 500);

      //draw a blue line that is not clipped
      context.strokeStyle = "blue"; //need list of available colors
      context.lineWidth = 5;
      context.arc(100, 100, 50, (Math.PI/180)*0, (Math.PI/180)*360, false);
      //full circle

The Canvas clipping region

Figure 2-10. The Canvas clipping region

Example 2-5 first draws a large 200×200 black rectangle onto the canvas. Next, we set our Canvas clipping region to rect(0,0,50,50). The clip() call then clips the canvas to those specifications. When we draw our full red circle arc, we only see the portion inside this rectangle. Finally, we set the clipping region back to rect(0,0,500,500) and draw a new blue circle. This time, we can see the entire circle on the canvas.


Other Canvas methods can be used with the clipping region. The most obvious is the arc() function:

arc(float x, float y, float radius, float startAngle,
float endAngle, boolean anticlockwise)

This can be used to create a circular clipping region instead of a rectangular one.

The best content for your career. Discover unlimited learning on demand for around $1/day.