HTML 5: Canvas as a place to play

imageI keep trying to write this post but just can’t get a solid start.  So stick with me, no matter what, I am posting something.

HTML 5 only supports one kind of shape: rectangle.  To draw other shapes you need to use paths like an arc.

Let’s draw a rectangle and a circle on a canvas, a very simple JavaScript function:

Code Snippet

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.    <title>Sq round</title>
  5.    <script type="text/javascript">
  6.        window.onload = function ()
  7.        {
  8.            var canvas = document.getElementById('canvas');
  9.            var context = canvas.getContext("2d");
  10.  
  11.           
  12.  
  13.            //Draw a circle using arc paths
  14.             context.arc(100, 100, 50, 0, 3 * Math.PI, false);
  15.            context.fillStyle = 'Green';
  16.            context.fill();   
  17.            
  18.             //Draw a rectangle, which is the only shape supported by HTML5
  19.             context.fillStyle = 'Black';
  20.            context.fillRect(0, 0, 100, 100);
  21.        };
  22.    </script>
  23. </head>
  24. <body>
  25.    <canvas id="canvas" width="400" height="200"></canvas>
  26. </body>
  27. </html>

 

This is a very simple example, when the page loads the function runs, normally you would have the javascript function placed somewhere else in the page.

The image in this blog is what you can see.  You might want to try changing the circle with the rectangle and see what happens. 

Also a word of caution, a number of tutorials, especially those on the mozillia pages have code that simply detects that IE 9 is running and throw up an alert to switch to safari or Firefox, as you can see IE 9 supports HTML 5 quite nicely.  Not saying that the tutorials out there are trying to make IE 9 look back, but I am not sure why they throw up the alert.

If you move the circle ahead of the rectangle it will be drawn on top of the rectangle.

  • The two new things in HTML 5 are:
    • <!DOCTYPE html>
      • this is all you have to use at the top of the page to define that the page is html.
    • <canvas id=”canvas” width=”400” height=”200”></canvas> 
      • this defines the new element in html 5, canvas which allows you to create animations, etc.

Make sure to check out: https://weblogs.asp.net/dwahlin/archive/2011/05/06/getting-started-with-the-html-5-canvas.aspx for more indepth discussions about HTML 5.