iphone development blog

Monday, January 7, 2008 @ 11:28 PM

Draw vector art using the canvas



We all know that the iPhone is incapable of displaying Flash content. But there are still two Flash-like benefits that we can take advantage of on the iPhone: vector art and animation. When Mac OS X 10.4 was released, Safari supported a new feature called the canvas. Safari, Firefox, Dashboard, and any Web Kit-based application (including the iPhone) can do arbitrary drawing of content using the canvas tag. This extension lets you reserve an area of your web page or widget and use rendering calls like those found in Quartz to paint complex paths and shapes in that area. The canvas tag was heavily utilized by the initial offering of Dashboard widgets released by Apple. Now you can use it to draw shapes to your iPhone webpages.

Don't get me wrong, this technique is not for amateurs. But if you're already familiar with using the Flash MX Drawing API, drawing using the canvas should be pretty easy. Additionally you can then use Javascript to continually redraw the canvas and animate your art.

Following is a silly example of what the canvas can do. Not very practicle, but go ahead and give it a whirl to see what it produces.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">

<script type="application/x-javascript">

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  for (i = 0; i < 6; i++) {
    for (j = 0; j < 6; j++) {
      ctx.fillStyle = 'rgb('+Math.floor(255-42.5*i)+','+Math.floor(255-42.5*j)+',0)';
      ctx.fillRect(j*25,i*25,25,25);
    }
  }
}

</script>
</head>

<body onload="draw()">

<canvas id="canvas"></canvas>

</body>

</html>


For more information on how to use the canvas, check out Mozilla's canvas tutorial. It's filled with static and animated examples. Enjoy!

http://developer.mozilla.org/en/docs/Canvas_tutorial

// Ryan Jennings

Labels: , , , ,


MindComet at 11:28 PM - View Post