Drawing in HTML5 With Canvas and Using HTML5 Audio and Video

By HTMLGoodies Staff  |  eMail Email    Print Print  Post a comment

Drawing in HTML5 using the Canvas element

Another new element in HTML5 is the <canvas> tag. It’s just what it sounds like——a blank surface for drawing. You need to use JavaScript to manipulate and draw on the canvas.

You may want to give your canvas element an id attribute so you can programmatically access it from your JavaScript code (or if you’re using jQuery and it’s the only canvas on the page, you could access it using $(‘canvas’) without needing to name it).

You can also (optionally) specify a height and a width for the canvas. Between the <canvas> and </canvas>, you can specify some text to display in browsers that don’t support the canvas element.

Here is a simple example of using the canvas to draw. (I’m attempting to draw the flag of Scotland. Please forgive any inaccuracies.)

<!DOCTYPE HTML>
<html>
<body>
    <canvas id="myCanvas">Your browser does not support the canvas tag.</canvas>
    <script type="text/javascript">

        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // Draw blue rectangle
        ctx.fillStyle = '#0065BD';
        ctx.fillRect(0, 0, 125, 75);

        // Draw white X
        ctx.beginPath();
        ctx.lineWidth = "15";
        ctx.strokeStyle = "white";
        ctx.moveTo(0, 0);
        ctx.lineTo(125, 75);
        ctx.moveTo(125, 0);
        ctx.lineTo(0, 75);
        ctx.stroke();

    </script>
</body>
</html>

Here’s what the code produces:

Image 1

Now let’s walk through the code.

First, I create the actual canvas and give it an ID of “myCanvas”. If this code were viewed in a browser that doesn’t support the HTML5 canvas element, it would display “Your browser does not support the canvas tag” instead of drawing the flag.

Next, I have a script. Remember, the canvas tag is only a container for graphics; you must use JavaScript to actually draw and render graphics on it. First, I grab a reference to the canvas using the “myCanvas” ID, and then get the canvas’s context which provides methods/properties for drawing and manipulating graphics on the canvas. I specified “2d” to use a 2-dimensional context to draw on the page.

Then, I draw the blue rectangle. I use fillStyle to specify the blue color. I use fillRect to draw the rectangle, specifying the size and position. Calling fillRect(0, 0, 125, 75) means: starting at position (0, 0)——the upper left-hand corner——draw a rectangle with width=125 pixels and height=75 pixels.

Finally, I draw the white X on the flag. I first call beginPath to start the process of painting a path. I specify a lineWidth of 15 pixels (using the guess-and-check method of trying different values until it looked correct) and a strokeStyle of “white” to make the path’s color white. Then I trace out the path using moveTo and lineTo. These methods position a “cursor” for you to draw; the difference is that moveTo moves the cursor without drawing a line and lineTo draws a line while moving. I start by moving to position (0, 0)——the upper left-hand corner——and then drawing a line to (125, 75)——the lower right-hand corner. Then I move to position (125, 0)——the upper right-hand corner——and draw a line to (0, 75)——the lower left-hand corner. Finally, the stroke method actually renders these strokes.

Quick Comparison of Canvas vs. SVG

Scalable Vector Graphics (SVG) is an earlier standard for drawing in a browser window. With the release of HTML5’s canvas, many people are wondering how they compare.

In my eyes, the biggest difference is that canvas uses immediate mode rendering and SVG uses retained mode rendering.

This means that canvas directly causes rendering of the graphics to the display. In my code above, once the flag is drawn, it is forgotten by the system and no state is retained. Making a change would require a complete redraw. In contrast, SVG retains a complete model of the objects to be rendered. To make a change, you could simply change (for example) the position of the rectangle, and the browser would determine how to re-render it. This is less work for the developer, but also more heavyweight to maintain a model.

The ability to style SVG via CSS in addition to JavaScript is worth calling out as another consideration. A canvas may be manipulated through JavaScript only.

Here is a high-level overview of other differences:

 

Canvas

SVG

Abstraction

Pixel-based (dynamic bitmap)

Shape-based

Elements

Single HTML element

Multiple graphical elements which become part of the Document Object Model (DOM)

Driver

Modified through Script only

Modified through Script and CSS

Event Model

User Interaction is granular (x,y)

User Interaction is abstracted (rect, path)

Performance

Performance is better with smaller surface and/or larger number of objects

Performance is better with smaller number of objects and/or larger surface

For a more detailed comparison, I want to point you to some sessions (from which I pulled this fabulous table, with permission):

Audio and Video Support

One of the big features that is new in HTML5 is the ability to support playing audio and videos. Prior to HTML5, you needed a plug-in like Silverlight or Flash for this functionality. In HTML5, you can embed audio and video using the new <audio> and <video> tags.

From a coding perspective, the audio and video elements are very simple to use. (I’ll give you a more in-depth look at their attributes below.) The audio and video elements are also supported in all major browsers (the latest versions of Internet Explorer, Firefox, Chrome, Opera, and Safari). However, the tricky part is that you need codecs to play audio and video, and different browsers support different codecs. (For a wonderful in-depth explanation of video containers and codecs, read http://diveintohtml5.org/video.html.)

Fortunately, this isn’t a show-stopper. The support for audio and video was implemented in a brilliant way, where there is support to try several different file formats (the browser will try each and then drop down to the next one if it can’t play it).

As a best practice, you should provide multiple sources of audio and video to accommodate different browsers. You can also fallback to Silverlight or Flash. Finally, any text between the opening and closing tags (such as <audio> and </audio>) will be displayed in browsers that do not support the audio or video element.

For example:

<audio controls="controls">
    <source src="laughter.mp3" type="audio/mp3" />
    <source src="laughter.ogg" type="audio/ogg" />
    Your browser does not support the audio element.
</audio>

With this code, the browser will first try to play the laughter.mp3 file. If it does not have the right codecs to play it, it will next try to play the laughter.ogg file. If the audio element is not recognized at all by the browser, it will display the text “Your browser does not support the audio element” where the audio control should be.

One caveat to audio and video: there is no built-in digital rights management (DRM) support; you have to implement this yourself as the developer. See this link from the W3C which explains their position (if you have a need for DRM content, also check out the Silverlight DRM documentation, which might be an easier solution).

Now let’s dive into each of these new elements.

Audio

First, let’s look at <audio> in more detail.

<audio controls="controls">
    <source src="laughter.mp3" type="audio/mp3" />
    <source src="laughter.ogg" type="audio/ogg" />
    Your browser does not support the audio element.
</audio>

We already discussed the fallback effect of trying each source until it hopefully finds one that can be played.

Note that there is a controls attribute. This will display audio playback controls including a play/pause button, the time, a mute button, and volume controls. In most situations, it’s good to display audio controls to the user; I hate visiting a website with sound and being unable to stop it, mute it, or turn it down. Don’t you?

Here’s what the audio controls look like in Internet Explorer:

Image 2

The controls look different in different browsers. Here are what they look like in Chrome (with a song playing). The drop-down volume pops down when you hover over the sound icon on the far right.

Image 3

Here are the controls in Firefox (with a song paused). Like Chrome, it also has a pop-up volume control (not shown) when you hover over the sound icon on the far right.

Image 4

Other fun attributes on the audio element include:

Attribute

Possible Values

Description

autoplay

autoplay

Starts the audio playing as soon as it’s ready

controls

controls

Displays audio playback controls on the page

loop

loop

Causes audio to repeat and play again every time it finishes

preload

auto, metadata, none

Determines whether to load the audio when the page is loaded. The valueauto will load the audio,metadata will load only metadata associated with the audio file, andnone will not preload audio. (This attribute will be ignored if autoplay is specified.)

src

(some URL)

Specifies the URL of the audio file to play

So this code sample would not only display audio playback controls, but also start the audio playing immediately and repeat it over and over in a loop.

<audio controls="controls" autoplay="autoplay" loop="loop">
    <source src="laughter.mp3" type="audio/mp3" />
    <source src="laughter.ogg" type="audio/ogg" />
    Your browser does not support the audio element.
</audio>

If you’d like to play around with the <audio> element yourself in your browser, there is a great “Tryit Editor” on http://w3schools.com that allows you to edit some sample code and see what happens. Or try the How to add an HTML5 audio player to your site article.

Video

Now, let’s examine the <video> element.

<video width="320" height="240" controls="controls">
    <source src="movie.ogg" type="video/ogg" />
    <source src="movie.mp4" type="video/mp4" />
    <source src="movie.webm" type="video/webm" />
    Your browser does not support the video tag.
</video>

</video>

As we discussed above, the video element has support for multiple sources, which it will try in order and then fall down to the next option.

Like audio, video has a controls attribute. Here is a screenshot of the video controls in Internet Explorer:

Image 5

Other fun attributes of the video element include:

Attribute

Possible Values

Description

audio

muted

Sets the default state of the audio (currently, “muted” is the only option)

autoplay

autoplay

Starts the video playing as soon as it’s ready

controls

controls

Displays video playback controls on the page

height

(value in pixels)

Sets the height of the video player

loop

loop

Causes video to repeat and play again every time it finishes

poster

(some URL)

Specifies the URL of an image to represent the video when no video data is available

preload

auto, metadata, none

Determines whether to load the video when the page is loaded. The valueauto will load the video,metadata will load only metadata associated with the video file, andnone will not preload video. (This attribute will be ignored if autoplay is specified.)

src

(some URL)

Specifies the URL of the video file to play

width

(value in pixels)

Sets the width of the video player

Again, to play around with the <video> element yourself, use the “Tryit Editor” from http://w3schools.com that allows you to edit some sample code and see what happens.

To learn more about video and audio, check out:

This article was reprinted with permission from Microsoft Corporation. This site does business with Microsoft Corporation.

Jennifer Marsman is a Developer Evangelist in Microsoft’s Developer and Platform Evangelism group, where she educates developers on Microsoft’s new technologies. Prior to becoming a Developer Evangelist, Jennifer was a software developer in Microsoft’s Natural Interactive Services division. In this role, she received two patents for her work in search and data mining algorithms. Jennifer has also held positions with Ford Motor Company, National Instruments, and Soar Technology.


Page 2 of 2

Previous Page
1 2
 

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  • HTML5 eBook

    HTML5 ebook

    HTML5 is the new standard that is expected to take over the Web. New versions of browsers are already starting to support the advanced features. Learn why HTML5 is important and discover how to use start using it today.
  • Html5 Logo