SVG with javascript

From Inkscape Wiki
Revision as of 02:18, 31 July 2008 by Juca (talk | contribs)
Jump to navigation Jump to search

In this tutorial I will explain how can you create SVG files in Inkscape and add javascript code to it so that you can have use it as a vectorial webpage with interactivity. Several browsers support SVG natively (Internet Explorer don't).


If you want to see an example of this technology try this: http://bighead.poli.usp.br/~juca/code/svg/minigame/minigame.svg I will focus on the techniques I used to develop this game.

First thing you should do is to create the art in Inkscape. In my case, I have drawn the handheld console and all of the sprites that appear in the grey LCD display.

Then you should select portions of the drawing which you want to control using javascript, group it and give it an id attribute. To group you use Ctrl+G, and to set a value for the id attribute you use ctrl+shift+O.

In my handheld game I have flashing lights. These lights are soft grey when off and dark grey when on. I could have used a single drawing and set its fill-color using javascript, but I prefered to have 2 copies of the sprite (one exactly over the other) and then hiding the top one when the sprite is unlit. Changing colour wouldnt be hard in the handheld example, but it definetly would in this other example of flashing lights: http://bighead.poli.usp.br/~juca/code/svg/pinball/PARTY-land.svg where sprites have different color and even some sprites have more than a single color.

So, I select one sprite, paint it in soft grey, duplicate it with ctrl+D, paint the duplicated sprite in dark grey, set a value to its id attribute with ctrl+shift+O (let's suppose I give it id="my_light") then I group both copies of the sprite so that I can keep stuff organized and easily manageable. I repeat this procedure to all sprites that I have in my SVG.

After that, we need to add javascript code to the SVG. Script code goes in the <script> tag. We open the svg file in a text editor and add:

<script xlink:href="myscript.js" />

and we also need to add onload="on_load(evt);" to the <svg> tag. This means that after the browser loads, it will call a javascript function called on_load.


Then we create the myscript.js file. It will contain the javascript code that will manipulate our SVG drawing in the browser.