web analytics
Contact me 
Orange D inside a circle

Raphaël Utilities

2013-03-14 05:30

I've made/adapted this library to import SVG directly from file and scale.

I've made/adapted this library because I was looking for an automatic way to convert SVG tag elements to Raphaël primitives to draw elements. All of the converters that are out there works in this way: you paste SVG tags into some textarea, clicks in convert and then you get all the javascript-raphaël code need it to build the SVG image. If you only need to display a SVG file (compatible with non-SVG browsers), this converters are for you.

But, what about parsing the file in real time, client-side, reading the SVG directly from the file? Well, I took Jonas Olmstead version of his SVG importer and made many changes to it in order to fit all my different scenarios.

This is the template that I use in many of my SVG projects as you can see in demo1, demo2 and demo3.

$(function() {
    var paper;
        type: 'GET',
        url: 'picture.xml', //this is the svg file loaded as xml
        dataType: 'xml',
        success: function(svgXML) {
            var svg = svgXML.getElementsByTagName('svg')[0];
            var width = svg.getAttribute('width'), height = svg.getAttribute('height');
            //'board' is the id of the SVG container (div in this case)
            paper = ScaleRaphael('board', width, height); //This create a scalable svg (changeSize function can be used as you see in next line)
            //Tricky way to adjust picture size to fill container width
            $('#board').css('width', '100%');
            paper.changeSize($('#board').width(), $('#board').width(), false, true);
            paper.importSVG(svg, {
                path: {
                    fill: '#fff'

I've added the following functions to this library so it can be more useful:

  • You can change rendered SVG size in runtime (thx ScaleRaphaël)
    function resizePaper(){
        var win = $(this);
        paper.changeSize($('#board').width(), $('#board').width(), false, true);
  • Multiple event bindings to Raphaël objects (mostly to handle the case of mobile support).
    paper.bindEvents(svgCity, 'mouseover,touchstart', function(el){
        this.attr({'fill': '#E0301E'});
  • moveScaledTo is a Raphael canvas extension to move a shape and scale it too.
    paper.moveScaledTo(elShape, newX, newY, 1.5); //scale 1.5 times
  • moveTo is a Raphael canvas extension to move a shape (keeping the same scale).
    paper.moveTo(elShape, newX, newY);
  • getLikeId is a Raphael canvas extension to returns you element by its internal ID (using like instead of equals as getById).
  • chrome is a Raphael canvas extension to fix small issue with texts in chrome.
  • beforeFn and afterFn events to be executed in each shape (more on demo3).