HTML 5: Canvas as a place to play
I 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
- <!DOCTYPE html>
- <html>
- <head>
- <title>Sq round</title>
- <script type="text/javascript">
- window.onload = function ()
- {
- var canvas = document.getElementById('canvas');
- var context = canvas.getContext("2d");
- //Draw a circle using arc paths
- context.arc(100, 100, 50, 0, 3 * Math.PI, false);
- context.fillStyle = 'Green';
- context.fill();
- //Draw a rectangle, which is the only shape supported by HTML5
- context.fillStyle = 'Black';
- context.fillRect(0, 0, 100, 100);
- };
- </script>
- </head>
- <body>
- <canvas id="canvas" width="400" height="200"></canvas>
- </body>
- </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.
- <!DOCTYPE html>
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.
Comments
Anonymous
September 01, 2011
great post ! thanksAnonymous
September 01, 2011
Thank Sanaulah, I see you are very active in the forums, this is indeed a nice compliment.Anonymous
September 01, 2011
Nice!Anonymous
September 06, 2011
Shinyo.her, Thank you for the "Nice!" comment, wish you would say more. Feel free to leave a link to your online presence (and anyone else who isn't a spammer) This is a free for all kind of blog although I realize that I can be a little harsh sometimes. If you have a project, etc. post the link!