Jayant's Blog

Monday, September 15, 2008

Simple SVG Shapes

Here's a simple test page which will draw different SVG shapes on your canvas. Of course if your iPhone OS is not 2.1, go get it and try out http://ecodevil.net/dev/blog/shapes.html. So lets looks at the code for http://ecodevil.net/dev/blog/svg.js.

Firstly, I have 3 JavaScript functions. The createNode is the main one which creates the appropriate SVG node using the node type and applies all properties from the argument hash to the new node. The createImage & createText are just specialized uses of this function.

function createNode(type, hash) {
var node = svg.appendChild(document.createElementNS("http://www.w3.org/2000/svg", type));
for (var key in hash) {
node.setAttribute(key, hash[key]);
return node;

function createImage(href, hash) {
var node = createNode("image", hash);
node.setAttributeNS("http://www.w3.org/1999/xlink", "href", href);
return node;

function createText(text, hash) {
var node = createNode("text", hash);
return node;

The next is the test function which is called on document.onload. It creates a rect, circle, ellipse, line, polyline, polygon, image, text & path. I've found the Pike's SVG Tutorial to be a good quick reference for SVG syntax.

function test() {
var div = document.getElementById("surface");
svg = div.appendChild(document.createElementNS("http://www.w3.org/2000/svg", "svg"));
svg.setAttribute("style", "left:0px; top:0px; width:320px; height:326px;");

createNode("rect", { x:10, y:10, width:50, height:30, fill:"rgb(0,255,0)" });
createNode("circle", { cx:95, cy:25, r:15, fill:"rgb(255,0,0)" });
createNode("ellipse", { cx:170, cy:25, rx:35, ry:15, fill:"rgb(0,0,255)" });
createNode("line", { x1:230, y1:10, x2:290, y2:40, stroke:"rgb(255,0,255)", "stroke-width":3 });
createNode("polyline", { points:"10,100 10,75 65,75 65,100 120,100 120,75 175,75 175,100 230,100 230,75 285,75 285,100", stroke:"rgb(0,255,255)", "stroke-width":3, fill:"none" });
createNode("polygon", { points:"10,125 285,165 285,125 10,165 10,125", fill:"rgb(255,255,0)" });

createImage("http://news.bbc.co.uk/shared/img/v4/header_blocks.gif", { x:10, y:190, width:107, height:32 });
createText("Ola World", { x:210, y:215, "font-size":32, "text-anchor":"middle", "font-weight":"bold" });
createNode("path", { d:"M10,265 L10,300 L100,265 C100,265 300,265 200,300 H285", stroke:"rgb(0,0,0)", "stroke-width":5, fill:"none" });

Thats it. You can try this page using Safari/Firefox/Opera or Chrome... not IE.

Labels: , ,


Post a Comment

Subscribe to Post Comments [Atom]


Create a Link

<< Home