Thursday, July 29, 2010

Using Canvas in Firefox and Safari for Graphics in your Browser

Using the Canvas Tag


About the Canvas Tag



The canvas tag is a 2d "canvas" that can be used to draw various vector shapes. It has a fully integrated javascript API. It somewhat resembles the graphical aspects of flash. Since adobe and flash have taken some flack lately, we begin to wonder what is the future of web graphics programming APIs? Apple seems to be in a space where they want to drop support for flash. (See iPad discussions). A lot of people are behind this movement. Another example is android, which does support flash, however many people are reporting that performance is bad.

Why Not Use the Canvas Tag?



Well, we can't replace flash with canvas. Flash has many other aspects such as full networking libraries, native video playback, audio, etc. Some of these things are coming along as separate modules for each browser but since there is no unified front on these modules, it seems to be lagging behind in terms of features, and even being available in the first place.

Another problem is we are not seeing much support for canvas using internet explorer (one of the most widely used browsers at the moment). Firefox, Safari, Chrome and Opera all fully support it.

Personally I would like to see canvas more widely used. And I think market forces may give it a bit of a push in the near future.

Demonstration of using the canvas tag. Works in Firefox and Safari



Hi Everyone,

Today I am going to demonstrate the use of the canvas tag in order to output graphics. Here is our template we will use in order to get started. This is a short script that will draw a circle at coordinates 200, 200 with a radius of 50. Below that is this code at work. It should be drawing a large blue circle if its working properly.



<html>
<head>
<title>Canvas Test</title>

<script type="application/javascript">
var ctx = null;

function draw() {
//get our canvas element
var canvas = document.getElementById("canvas");
//create our context
ctx = canvas.getContext("2d");
//set out fill color, red = 0, green = 0, blue = 200, alpha = 0.5
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
//begin our arc
ctx.beginPath();
//draw an arc, starting at 200, 200. 50 radius, angle starts at 0, and continues to 360 degrees (a cicle), and uses counter clockwise (false)
ctx.arc(200, 200, 50, 0, (Math.PI/180)*360, false);
//end our path
ctx.closePath();
//fill in the result
ctx.fill();


}
</script>

</head>

<body onload="draw()">
<style>
canvas,
body {
margin: 0px;
padding: 0px;
}
canvas {
border: solid 1px;
}
</style>
<canvas width="800" height="600" id="canvas"></canvas>
</body>
</html>


Here is the example at work:



Please leave your comments below!

No comments:

Post a Comment