Friday, October 31, 2008

Scaling SVG Graphics with Javascript (2)

In the previous posting, I have provided a demo example how to add scripts to scale svg grphics. I was going to add svg graphics in my blog and to show the scaling feature. However, I struggled for two days to make it working but without luck.

I can add script functions to my blog through Blogger's layout settings. In this sense, I have control of my HTML page. Here I mean by having control of HTML page is that you can edit and update the HTML page to web sever. However, I cannot find a way to submit svg graphics to my Blogger server. What I tried was to upload my svg to another site, Open Clip Art Library. I added my scripts to a svg xml graphic.

This brings a problem: my Blogger and my svg are in two different sites. What I found out is that the scripts in my blog does not have access to the scripts in my svg file. JavaScript has security reason to prevent calling scripts on other sites. What have been working in my local computer as shown in the demo would not work any more when I changed the svg reference to a different site!

In order to make this working, you have to put svg in your site.

Anyway, the instructions in my demo still work well if you follow this rule: you have the control of both html and svg files on one site.

The demo shows you a way to attach script functions defined in svg to the object in your html file. In JavaScript world, anything is object. A tag <object> is a DOM element. It also can be obtained by DOM documention object's getElementById() method. The unique feature of JavaScript is that you can attach or detach a function as a method to a object dynamically! That's basic technique I used in the demo. In this way, you can control the scale of svg from your html page.

That is one way to do it. I further investigated an alternative way to scale svg: adding scripts to a svg xml file. This provides some UIs in the svg: two small circles on the top-left corner the svg graphic with some mouse events(mouseover, mouseout and mouseup for click). By clicking on the left circle, it will scale down the svg; while clicking on the right circle, scaling up the svg.

I thought there is no attachment from my html and svg. The scripts in svg should be able to work. Nop! Since the svg is referenced by another site, any function or DOM method calls stop working.

Here is my svg with scripts at Open Clip Art Library. I put it here but the scripts in the svg do not work:

This browser does not support svg. You may need to download FireFox or get Adobe's plugin if you use IE

Open the dog graphic in another tab or browser window. Try it out and enjoy it!

NOTE: don't zoom in or scale the svg too big. It will slow down your browser for minutes. I event got crash once! If you scale too small or too big, refresh the page to restore to its original size.