Quantcast
Channel: Sanbeiji » html
Viewing all articles
Browse latest Browse all 4

A quick introduction to the HTML5 Canvas

$
0
0

The next article in the Developing with HTML5 series. Better late than never, but much has happened. Perhaps more on that someday…

A painter paints his pictures on canvas. But musicians paint their pictures on silence. We provide the music, and you provide the silence.

—Leopold Stokowski

HTML5’s canvas element allows us to create and display images on-the-fly using JavaScript. Canvas graphics can often yield speedy performance, particularly on mobile devices and desktops that feature browsers with hardware acceleration enabled. While SVG (which I covered earlier) does feature a convenient model for markup and CSS access to the graphic in question, Canvas can usually do a better job at performance thanks to hardware acceleration and not having to traverse the DOM.

Let’s analyze a basic canvas. Start with a new HTML5 document containing a canvas element in the body:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Canvas</title>
</head>
<body>
    <canvas id="example" width="250" height="250">
      This is my canvas.
    </canvas>
</body>
</html>

Save your file. Not much will happen yet, unless you have web browser that doesn’t support canvas. Modern browsers will probably yield a blank white page for the above code. An older non-supporting browser, a text-only browser such as Lynx, or a screen reader will deliver the default text:

Lynx renders default text for canvas

You can draw on the canvas using JavaScript. Place this code above the closing element to try it out:

<script>
  function draw() {
    var canvas = document.getElementById("example");
    if (canvas.getContext) {
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "rgb(0,255,0)";
      ctx.fillRect (10, 10, 220, 220);
    } 
  }
  window.onload = draw;
</script>

Now when we preview our page in a supporting browser, we should see a green box:

Green canvas box

To explain what we did with this JavaScript: We wrote a function called draw(), which first uses the d ocument.getElementById() method to grab our #example canvas element. The next line sets the rendering context with canvas.getContext(). We then use the fillStyle() method to assign a CSS color value and the fillRect() method to draw the box.

The prototype for fillRect() is fillRect(x, y, width, height). The x and y values position the box relative to the bounds of the canvas, and the
box is drawn from there using width and height.

Now let’s try a circle. (And throw in some alpha transparency for good measure.) Add five more lines to our ctx variable as shown:

function draw() {
  var canvas = document.getElementById("example");
  if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgb(0,255,0)";
    ctx.fillRect (10, 10, 220, 220);
    <!-- Add the following 5 lines of code: -->
    ctx.fillStyle = "rgba(255,0,255,0.5)";
    ctx.beginPath();
    ctx.arc(175,120,75,0,Math.PI*2,false);
    ctx.closePath();
    ctx.fill();
  }
}

The result should be an overlapping circle

Progress of canvas showing circle overlapping rectangle

Here, we’ve used the fillStyle() element to define a light violet color for our circle. You’ll notice that this time we are passing in one extra number to fillStyle(). That extra number is a parameter that sets the alpha transparency—any decimal value from 0 to 1 is valid, with 0 being fully transparent and 1 being fully opaque.

In this case, our value of 0.5 might be thought of as a 50% transparency. We see the true violet color of our circle along the right edge where it hangs off of our green square, and we see a blend of the two colors (which happens to be a neutral gray) where the two shapes overlap.

Because we want to create a circle instead of a square in this example, we need to use the beginPath() and closePath() methods to draw a linear shape. We use the arc() method for defining the path itself. The first two values in the arc() arguments are x and y coordinates within the canvas. Third is the arc radius, which here is set to 75 pixels. The last two values are the start angle and end angle. We can specify a calculation for these angles, so here we set our end angle by leveraging JavaScript’s built-in Math object to multiply pi by 2.

Now let’s add a regular jpeg image to our canvas after our circle (below the last ctx.fill() line):

var piano = new Image();
piano.src = "piano.jpg";
piano.onload = function() {
  ctx.drawImage(piano, 30, 30);
}

piano keys closeupThis adds our piano image (shown here—please feel free to download for use with this tutorial) to the canvas. Above, we begin by initializing a new instance of the Image object. The src property specifies the path to our image (which may be relative or absolute). Next, the onload property tells the canvas to execute the drawImage() method, specifying our piano image as the source and x and y coordinates of 30 pixels each.

But why is that special? After all, we could have just inserted an <img> tag there, right? Yeah, but since this is JavaScript, we can clone it. Here’s how to add another instance of the image using different parameters:

var piano = new Image();
piano.src = "piano.jpg";
piano.onload = function() {
  ctx.drawImage(piano, 30, 30);
  ctx.drawImage(piano, 100, 130, 70, 70);
}

We’ve resized our cloned image, too. (It’s now 70 pixels square.) And now we can apply effects to it. How about trying a little drop shadow?

var piano = new Image();
piano.src = "piano.jpg";
piano.onload = function() {
  ctx.drawImage(piano, 30, 30);
  ctx.drawImage(piano, 100, 130, 70, 70);
  ctx.shadowOffsetX = 0;
  ctx.shadowOffsetY = 5;
  ctx.shadowBlur = 30;
  ctx.shadowColor = "#000";
}

Here’s our finished masterpiece:

A rectangle, circle and two copies of a piano keyboard image composed onto the HTML5 canvas

And that is what modern art is all about. Here’s our final code example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Canvas</title>
</head>
<body>
  <canvas id="example" width="250" height="250">
    This is my canvas.
  </canvas>
</body>
  <script>
    function draw() {
      var canvas = document.getElementById("example");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "rgb(0,255,0)";
        ctx.fillRect (10, 10, 220, 220);
        ctx.fillStyle = "rgba(255,0,255,0.5)";
        ctx.beginPath();
        ctx.arc(175,120,75,0,Math.PI*2,false );
        ctx.closePath();
        ctx.fill();
        var piano = new Image();
        piano.src = "piano.jpg";
        piano.onload = function() {
          ctx.drawImage(piano, 30, 30);
          ctx.drawImage(piano, 100, 130, 70, 70);
        }
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 5;
        ctx.shadowBlur = 30;
        ctx.shadowColor = "#000";
      } 
    }
    window.onload = draw;
  </script>
</html>

This is just the tip of the iceberg—but it should be enough to show how to get a basic canvas working in HTML5.

The canvas element is fairly well supported on modern versions of most web browsers, including Firefox, Safari, Chrome, and Opera. This goes as well for their mobile equivalents, with the exception that the Text API for canvas has spotty support for Opera Mini.

Internet Explorer 9 even includes support for the canvas element. For older versions of IE, add Explorercanvas as a source to your web page and you’ll achieve pretty good compatibility out of the box. You can check current browser support for canvas features on caniuse.com


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images