Vector graphics with HTML5 canvas
The new HTML
<canvas> element that is part of the
HTML5 specification enables the creation of dynamic graphics with a
simplicity that has not been available prior to now. Although it may take some
time before browsers support all the features of the canvas element, some of
it’s capabilities can be utilized today.
The canvas element supports both vector and bitmap graphic creation, and in this article I will demonstrate how to use the vector graphic capabilities to create a simple image.
Creating the Canvas Element
The HTML tag used to create a canvas element is
<canvas width="300" height="200"></canvas>
<canvas id="canvas1" width="300" height="200" style=" border: 1px solid #808080; background: #ffffff; " ></canvas>
Which gives us the following:
Vector graphics are drawn on the canvas using a coordinate system. The coordinate system can be redefined in any way that you desire, however it is initially defined with the origin in the top left corner.
Our canvas is 300 pixels wide and 200 pixels high. Since the coordinate (0, 0) is located in the top left corner, the coordinate (300, 200) will be the bottom right corner.
var canvas = document.getElementById('canvas1');
Now we need to access the 2D graphics layer of the canvas element:
ctx = canvas.getContext('2d');
This 2D layer supports either vector or bitmap graphics. This example will utilize vector drawing functions.
Drawing On the Canvas
Now we can set the line width and stroke color:
ctx.lineWidth = "2"; ctx.strokeStyle = "#ff0000";
And finally draw a line across the canvas:
ctx.beginPath(); ctx.moveTo(50, 100); ctx.lineTo(250, 100); ctx.stroke();
Putting It Together
var canvas = document.getElementById('canvas1'); var ctx = canvas.getContext('2d'); ctx.lineWidth = "2"; ctx.strokeStyle = "#ff0000"; ctx.beginPath(); ctx.moveTo(50, 100); ctx.lineTo(250, 100); ctx.stroke();