Wednesday, August 22, 2012

Canvas Simplified

Canvas Simplified

Canvas has some really complex examples.

This post is intended to explain using Canvas to animate a space ship with javascript for the non-expert.

I earlier blogged how to animate using SVG. With SVG you can get the image you drew by it's svg-dom id and delete it, then draw another one. Or just update its x,y coordinates!

Canvas however is a little harder. You have to draw over the old image to erase it, then draw the new one at the new coordinates.

You want to draw whatever was behind the image in order to erase it. For my example I used a solid white background so drawing a solid white image the same size as the original is my approach.

Here it is on jsfiddle in case you want to just see it run. http://jsfiddle.net/uponthecouch/2JXJr/4/

Sometimes it is handy to have the entire thing in a single file such as you could put in an eclipse Static Web Project and try out by just pressing the play button right on our own machine:
 
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>SVG attempt</title>
  <style>
   #canvasContainer 
   {
       width: 600px;
       height: 200px;
       background-color: white;
       border:1px solid black;
   }
  </style>
 </head>
 <body>
  <canvas id="canvasContainer">
  </canvas>
  <p>X coordinate: <span id="xcoor"></span>
  <p>Y coordinate: <span id="ycoor"></span>
  <script type="text/javascript">
   var canvas = document.getElementById("canvasContainer");
   var context = canvas.getContext('2d');
   var image = new Image();
   var clearImage = new Image();
   clearImage.src = "icons/shipClear.png";
   var x=0;
   var y=0;
   image.onload = function()
   {
    context.drawImage(image, x, y);
   };
   image.src = 'icons/shipNE.png';
   var timer = self.setInterval(function()
   {
       move_image();
   }, 100);
   
   function move_image()
   {
    context.drawImage(clearImage, x, y);
    x += 2;
    y += 2;
       if (y>200)
       {
           timer = window.clearInterval(timer)
           return;
       }
       context.drawImage(image, x, y);
       document.getElementById("xcoor").innerHTML = x;
       document.getElementById("ycoor").innerHTML = y;
   }
  </script>
 </body>
</html>

No comments: