Pebbles

Pebbles gather along the outline of the word SVG, then travel to spell Wow.

What you are seeing

A gray panel with a play button in its lower right corner. After play, small shaded pebbles appear one by one until they trace the word SVG. A click on the panel sends them along to form the word Wow.

How it works

Two hidden paths hold the outlines of the words SVG and Wow.

The script samples 250 evenly spaced points along each path with getPointAtLength.

Each pebble is a circle with a shared radial gradient and a small random offset.

A timer jitters the pebbles and blends their positions from the first word to the second.

History

Posted on October 4, 2009, to illustrate the path measurement methods of the SVG DOM.

Source

/path/pebbles.svg
<?xml version="1.0" encoding="UTF-8"?>
<!-- ======================================================================= -->
<!-- Vincent Hardy                                                           -->
<!--  License terms: see svg-wow.org                                         -->
<!-- CC0 http://creativecommons.org/publicdomain/zero/1.0/                   -->
<!-- ======================================================================= -->
<svg width="100%" height="100%" viewBox="0 0 800 550"
     style="background:#0f0f0a"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     onload="sw.init();init();">
<title>Pebbles</title>
<desc>Two hundred and fifty shaded pebbles placed along the outline of the word SVG with getPointAtLength. They jitter once started, and a click on the background moves them along to spell Wow.</desc>

<rect width="100%" height="100%" fill="#0f0f0a" />

<svg width="800" height="550" x="0" y="0" viewBox="0 0 800 550"
     xmlns="http://www.w3.org/2000/svg" overflow="visible"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:sw="http://www.svgopen.org/2004/svgWow"
     xmlns:xlink="http://www.w3.org/1999/xlink">
    <script xlink:href="../res/2.0/scripts/dom-utils.js" />
    <script xlink:href="pebbles.js" />

	<defs>
        <radialGradient id="ballPaint"
               gradientUnits="objectBoundingBox"
               fx=".2" fy=".2" r=".5">
            <stop offset="0%" style="stop-color:white" />
            <stop offset="20%" style="stop-color:#a0a0a0" />
            <stop offset="100%" style="stop-color:black" />
        </radialGradient>
        <radialGradient id="backgroundGradient"
               gradientUnits="objectBoundingBox"
               cx="-0.5" cy="-0.5" fx=".2" fy=".2" r="2.3">
            <stop offset="0%" style="stop-color:#dddddd" />
            <stop offset="20%" style="stop-color:#c0c0c0" />
            <stop offset="100%" style="stop-color:#0a0a0a" />

        </radialGradient>
        <linearGradient id="backgroundGradientCast"
               gradientUnits="objectBoundingBox"
               x1="0" y1="0" x2="0.2" y2="1">
            <stop offset="0%" stop-color="black" stop-opacity="0" />
            <stop offset="50%" stop-color="black" stop-opacity="0" />
            <stop offset="100%" stop-color="black" stop-opacity="0.5"/>

        </linearGradient>

    </defs>
        <g transform="translate(100,75)" >
            <rect x="0" y="0" width="600" height="400"
                  fill="url(#backgroundGradient)" rx="5" ry="5"
                  onclick="movingToDst = true;"/>

            <g transform="translate(35.714286,-7.1428571)">
                <path
                     id="svgPath"
                     d="M 37.372857,249.70286 C 48.842846,255.90285 66.512877,260.55286 86.352857,260.55286 C 129.75282,260.55286 151.76286,239.78283 151.76286,211.26286 C 151.45286,189.25288 139.67283,174.37285 110.84286,164.45286 C 92.242877,157.94286 86.352857,154.22285 86.352857,146.78286 C 86.352857,139.34287 92.862867,134.69286 104.33286,134.69286 C 117.04285,134.69286 130.37287,139.65287 137.19286,143.37286 L 145.25286,110.82286 C 135.95287,106.17287 120.45284,101.83286 102.78286,101.83286 C 65.272897,101.83286 41.092857,123.22289 41.092857,151.74286 C 40.782857,169.72284 52.872889,186.77287 84.492857,197.31286 C 101.85284,203.20285 106.50286,206.92287 106.50286,214.98286 C 106.50286,222.73285 100.61285,227.38286 86.352857,227.38286 C 72.402867,227.38286 54.422848,221.49285 45.742857,216.22286 L 37.372857,249.70286 M 164.34692,105.55286 L 219.52692,257.14286 L 266.64692,257.14286 L 323.06692,105.55286 L 273.46692,105.55286 L 253.93692,175.92286 C 250.52693,188.94284 248.04692,200.41287 245.56692,212.81286 L 244.63692,212.81286 C 242.15692,200.72287 239.67692,188.94284 235.95692,175.92286 L 215.49692,105.55286 L 164.34692,105.55286 M 483.84067,150.81286 C 483.84067,128.18288 484.46067,115.47285 485.08067,105.55286 L 444.16067,105.55286 L 442.61067,123.84286 L 441.99067,123.84286 C 434.24068,111.13287 421.22065,102.14286 400.45067,102.14286 C 362.94071,102.14286 331.63067,133.14291 331.63067,182.12286 C 331.63067,225.52281 358.29071,255.90286 395.80067,255.90286 C 413.16066,255.90286 427.73068,248.77285 436.72067,236.37286 L 437.34067,236.37286 L 437.34067,245.98286 C 437.34067,274.19283 420.29065,285.97286 397.97067,285.97286 C 379.99069,285.97286 363.56066,280.08285 353.95067,274.50286 L 344.65067,310.46286 C 358.29066,317.90285 379.06069,321.93286 399.21067,321.93286 C 421.53065,321.93286 444.16069,317.59284 460.59067,303.33286 C 477.95066,288.14287 483.84067,264.27283 483.84067,235.13286 L 483.84067,150.81286 M 436.72067,189.56286 C 436.72067,193.59285 436.41067,198.55286 435.17067,202.27286 C 432.07068,213.12285 422.46066,221.18286 410.06067,221.18286 C 390.53069,221.18286 379.37067,203.51283 379.37067,180.88286 C 379.37067,153.29288 393.01069,137.79286 410.37067,137.79286 C 423.39066,137.79286 432.38068,146.16287 435.79067,158.56286 C 436.41067,161.35285 436.72067,164.45286 436.72067,167.24286 L 436.72067,189.56286"
                     style="display:none" />
                <path
                     id="wowPath"
                     d="M 33.905388,155.83787 L 62.505387,253.63787 L 91.105387,253.63787 L 100.90539,219.23787 C 103.30539,210.23788 105.30539,201.03786 107.10539,188.83787 L 107.50539,188.83787 C 109.50539,201.03786 111.30539,209.83788 113.90539,219.43787 L 123.10539,253.63787 L 151.50539,253.63787 L 181.50539,155.83787 L 151.70539,155.83787 L 143.50539,194.63787 C 141.10539,205.83786 139.10539,217.03788 137.70539,228.03787 L 137.30539,228.03787 C 135.50539,216.83788 132.90539,206.03786 130.10539,194.83787 L 120.30539,155.83787 L 96.305387,155.83787 L 85.905387,196.23787 C 83.705387,205.83786 80.705387,216.83788 78.905387,228.03787 L 78.305387,228.03787 C 76.705387,216.83788 74.705387,206.03786 72.905387,196.03787 L 64.905387,155.83787 L 33.905388,155.83787 M 239.53352,153.43787 C 207.93355,153.43787 187.13352,173.6379 187.13352,205.43787 C 187.13352,237.03784 209.13354,255.83787 237.73352,255.83787 C 263.93349,255.83787 289.33352,239.43783 289.33352,203.63787 C 289.33352,174.0379 269.33349,153.43787 239.53352,153.43787 M 238.53352,175.23787 C 252.3335,175.23787 257.93352,190.03788 257.93352,204.43787 C 257.93352,222.23785 250.5335,234.03787 238.53352,234.03787 C 225.53353,234.03787 218.53352,221.43785 218.53352,204.63787 C 218.53352,190.23788 224.13353,175.23787 238.53352,175.23787 M 296.01477,155.83787 L 324.61477,253.63787 L 353.21477,253.63787 L 363.01477,219.23787 C 365.41476,210.23788 367.41477,201.03786 369.21477,188.83787 L 369.61477,188.83787 C 371.61476,201.03786 373.41477,209.83788 376.01477,219.43787 L 385.21477,253.63787 L 413.61477,253.63787 L 443.61477,155.83787 L 413.81477,155.83787 L 405.61477,194.63787 C 403.21477,205.83786 401.21476,217.03788 399.81477,228.03787 L 399.41477,228.03787 C 397.61477,216.83788 395.01476,206.03786 392.21477,194.83787 L 382.41477,155.83787 L 358.41477,155.83787 L 348.01477,196.23787 C 345.81477,205.83786 342.81476,216.83788 341.01477,228.03787 L 340.41477,228.03787 C 338.81477,216.83788 336.81476,206.03786 335.01477,196.03787 L 327.01477,155.83787 L 296.01477,155.83787 M 483.96789,209.43787 L 488.36789,118.83787 L 456.76789,118.83787 L 461.16789,209.43787 L 483.96789,209.43787 M 472.56789,255.83787 C 483.36788,255.83787 490.36789,248.03786 490.36789,237.63787 C 490.16789,226.83788 483.16788,219.43787 472.56789,219.43787 C 461.9679,219.43787 454.56789,226.83788 454.56789,237.63787 C 454.56789,248.03786 461.7679,255.83787 472.16789,255.83787 L 472.56789,255.83787"
                     style="display:none" />
                <g id="markers" fill="url(#ballPaint)" stroke="none" fill-opacity="1">
                </g>
            </g>

            <text id="pebblesHint" x="300" y="210" text-anchor="middle" fill="#fff" fill-opacity="0.85"
                  pointer-events="none" font-family="'Helvetica Neue', Arial, sans-serif" font-size="17">Press play, then click the background</text>

            <g transform="translate(563,363)" onclick="stopOrGo()" style="cursor:pointer">
                <!-- From http://openclipart.org/media/files/Anonymous/12966 -->
                <!-- Pause button created from the next one                  -->
                <image id="play" display="inline"
                    xlink:href="../res/2.0/icons/OpenClipArt/Anonymous_Button_Next.png"
                    width="32" height="32" />
                <image id="pause" display="none"
                    xlink:href="../res/2.0/icons/OpenClipArt/Anonymous_Button_Pause.png"
                    width="32" height="32" />
            </g>

            <g
               id="g3716"
               transform="translate(35.7,-7)">
            </g>

        </g>
</svg>

</svg>
/path/pebbles.js
/** =======================================================================
 *  Vincent Hardy
 *  License terms: see svg-wow.org
 *  CC0 http://creativecommons.org/publicdomain/zero/1.0/
 *  ======================================================================= */
var svgNS = "http://www.w3.org/2000/svg";

function init() {
    var srcPath = document.getElementById("svgPath");
    var dstPath = document.getElementById("wowPath");
    var srcPathLength = srcPath.getTotalLength();
    var dstPathLength = dstPath.getTotalLength();

    var markers = document.getElementById("markers");
    var n = 250;


    var srcGap = srcPathLength / n;
    var dstGap = dstPathLength / n;

    var minR = 2;
    var deltaR = 5;
    var dPos = 4;
    var dots = [];

    for (var i = 0; i < n; i++) {
        var dot = document.createElementNS(svgNS, "circle");
        dots.push(dot);
        var coords = srcPath.getPointAtLength(srcGap * i);
        var dstCoords = dstPath.getPointAtLength(dstGap * i);
        var thetaX = Math.random() * Math.PI * 2;
        var thetaY = Math.random() * Math.PI * 2;
        var dx = Math.cos(thetaX) * dPos;
        var dy = Math.cos(thetaY) * dPos;
        // Radius factor in the [0, 1] range: pebbles far from the path are smaller.
        var dr = 1 - Math.sqrt(dx * dx + dy * dy) / (dPos * Math.SQRT2);

        dot.setAttributes({
            r: minR + dr * deltaR,
            cx: coords.x + dx,
            cy: coords.y + dy,
            display: "none"
        });

        if (Math.random() > 0.5) {
            dot.growingFactor = 1;
        } else {
            dot.growingFactor = -1;
        }
        dot.radius = minR + dr * deltaR;
        dot.thetaX = thetaX;
        dot.thetaY = thetaY;
        dot.coords = coords;
        dot.srcCoords = coords;
        dot.dstCoords = dstCoords;
        
        markers.appendChild(dot);
    }

    randomShow = getRandomShow(dots);

    dotInterpolator = getDotInterpolator(dots, minR + 0.5 * deltaR, minR);
}

var showRunningId = undefined;

var runningId = undefined;
var dotInterpolator = undefined;

function getRandomShow (dotsArray) {
    var dots = [].concat(dotsArray);

    return function () {
        for (var i = 0; i < 1; i++) {
            if (dots.length === 0) {
                clearInterval(showRunningId);
                break;
            } else {
                var dotIndex = Math.floor(Math.random() * dots.length);
                dots[dotIndex].setAttribute("display", "inline");
                dots.splice(dotIndex, 1);
            }
        }
    }
}

var movingToDst = false;
var srcToDstRatio = 0;


function getDotInterpolator (dots, maxR, minR) {
    var nDots = dots.length;

    return function () {
        for (var i = 0; i < nDots; i++) {
            var growNow = (Math.random(1) > 0.5 ? true : false);
            var p = srcToDstRatio;
            var np = 1 - p;
            var dPos = 2;

            var dot = dots[i];
            if (growNow === true) {                
                var r = dot.radius + dot.growingFactor * 0.25;
                if (r > maxR) {
                    dot.growingFactor = -1;
                } else if (r < minR) {
                    r = minR;
                    dot.growingFactor = 1;
                }
                dot.setAttribute("r", r);
                dot.radius = r;
            } else {
                dot.thetaX = (dot.thetaX + Math.PI / 20) % (2 * Math.PI);
                dot.thetaY = (dot.thetaY + Math.PI / 20) % (2 * Math.PI);
                dot.setAttribute("cx", np * dot.coords.x + p * dot.dstCoords.x + Math.cos(dot.thetaX) * dPos);
                dot.setAttribute("cy", np * dot.coords.y + p * dot.dstCoords.y + Math.cos(dot.thetaY) * dPos);
            }
        }

        if (movingToDst === true) {
            srcToDstRatio += 0.08;
            if (srcToDstRatio >= 1) {
                srcToDstRatio = 1;
                movingToDst = false;
            }
        }
    };
}

function stopOrGo () {
    if (showRunningId === undefined) {
        showRunningId = setInterval(randomShow, 40);
    }
    
    document.getElementById("pebblesHint").setAttribute("display", "none");

    if (runningId !== undefined) {
        clearInterval(runningId);
        runningId = undefined;
        document.getElementById("play").setAttribute("display", "inline");
        document.getElementById("pause").setAttribute("display", "none");
    } else {
        runningId = setInterval(dotInterpolator, 40);
        document.getElementById("play").setAttribute("display", "none");
        document.getElementById("pause").setAttribute("display", "inline");
    }
}

// Keyboard: space plays or pauses, Enter moves the pebbles to the next word.
document.addEventListener("keydown", function (evt) {
    if (evt.key === " ") {
        stopOrGo();
    } else if (evt.key === "Enter") {
        movingToDst = true;
    } else {
        return;
    }
    evt.preventDefault();
}, false);
/res/2.0/scripts/dom-utils.js
/** =======================================================================
 *  Vincent Hardy
 *  License terms: see svg-wow.org
 *  CC0 http://creativecommons.org/publicdomain/zero/1.0/
 *  ======================================================================= */

(function () {
    // Use the sw (svgWow!) prefix for all the library.
    window.sw = window.sw ? window.sw : {};

    /**
     * Global function for getting an element by id concisely.
     */
    if (window.$ === undefined) {
        window.$ = function (id) {
            return document.getElementById(id);
        };
    }
    // Namespace constants
    sw.svgNS = "http://www.w3.org/2000/svg";
    sw.xlinkNS = "http://www.w3.org/1999/xlink";
    sw.wowNS = "http://www.svgopen.org/2004/svgWow";
    sw.xhtmlNS = "http://www.w3.org/1999/xhtml";
    
    // Default namespace prefixes
    var defaultNamespacePrefixes = {
        svg: sw.svgNS,
        xlink: sw.xlinkNS,
        sw: sw.wowNS,
        xhtml: sw.xhtmlNS
    };

    // =========================================================================
    // DOM Helpers
    // =========================================================================
    sw.firstElement = function () {
        var c = this.firstChild;
        var result = null;

        while (c !== null) {
            if (c.nodeType === Node.ELEMENT_NODE) {
                result = c;
                break;
            }
            c = c.nextSibling;
        }

        return result;
    };

    sw.nextElement = function () {
        var s = this.nextSibling;
        var result = null;

        while (s !== null) {
            if (s.nodeType === Node.ELEMENT_NODE) {
                result = s;
                break;
            }
            s = s.nextSibling;
        }

        return result;
    };

    sw.prevElement = function () {
        var s = this.prevSibling;
        var result = null;

        while (s !== null) {
            if (s.nodeType === Node.ELEMENT_NODE) {
                result = s;
                break;
            }
            s = s.prevSibling;
        }

        return result;
    };

    sw.removeAllChildren = function () {
        var c = this.firstChild;
        var nc;
        while (c !== null) {
            nc = c.nextSibling;
            this.removeChild(c);
            c = nc;
        }
    };

    sw.getMatrix = function () {
        var m = undefined, txf, svg;
        if (this.transform !== undefined) {
            txf = this.transform.baseVal.consolidate();
            if (txf === null) {
                svg = this.ownerSVGElement;
                m = svg.createSVGMatrix();
                txf = this.transform.baseVal.createSVGTransformFromMatrix(m);
                this.transform.baseVal.initialize(txf);
            } else {
                m = txf.matrix;
            }
        }
        return m;
    }

    sw.setMatrix = function (m) {
        var txf, svg;
        if (this.transform !== undefined) {
            svg = this.ownerSVGElement;
            txf = this.transform.baseVal.createSVGTransformFromMatrix(m);
            this.transform.baseVal.initialize(txf);
        }
        return this;
    }

    sw.getShowHandler = function () {
        var that = this;
        return function () {
            that.setAttribute("display", "inline");
        }
    };

    sw.getHideHandler = function () {
        var that = this;
        return function () {
            that.setAttribute("display", "none");
        }
    };

    /**
     * Global function for toggling the current display value.
     *
     * @param id the id of the element whose display should be toggled between
     *        'block' and 'none'
     */
    function toggleDisplay(id) {
        var elm = $(id);
        if(elm) {
            elm.style.display = (elm.style.display == "none" ? "block" : "none");
        }
    }

    // =============================================================================
    // Simple SVG API
    //
    // @see: http://www.w3.org/Graphics/SVG/WG/wiki/Simple_SVG_API
    // =============================================================================

    // List of SVG elements on which the setAttributes method is made available
    sw.svgElements = [
        "a",
        "altGlyph",
        "altGlyphDef",
        "altGlyphItem",
        "animate",
        "animateColor",
        "animateMotion",
        "animateTransform",
        "circle",
        "clipPath",
        "color-profile",
        "cursor",
        "definition-src",
        "defs",
        "desc",
        "ellipse",
        "feBlend",
        "feColorMatrix",
        "feComponentTransfer",
        "feComposite",
        "feConvolveMatrix",
        "feDiffuseLighting",
        "feDisplacementMap",
        "feDistantLight",
        "feFlood",
        "feFuncA",
        "feFuncB",
        "feFuncG",
        "feFuncR",
        "feGaussianBlur",
        "feImage",
        "feMerge",
        "feMergeNode",
        "feMorphology",
        "feOffset",
        "fePointLight",
        "feSpecularLighting",
        "feSpotLight",
        "feTile",
        "feTurbulence",
        "filter",
        "font",
        "font-face",
        "font-face-format",
        "font-face-name",
        "font-face-src",
        "font-face-uri",
        "foreignObject",
        "g",
        "glyph",
        "glyphRef",
        "hkern",
        "image",
        "line",
        "linearGradient",
        "marker",
        "mask",
        "metadata",
        "missing-glyph",
        "mpath",
        "path",
        "pattern",
        "polygon",
        "polyline",
        "radialGradient",
        "rect",
        "script",
        "set",
        "stop",
        "style",
        "svg",
        "switch",
        "symbol",
        "text",
        "textPath",
        "title",
        "tref",
        "tspan",
        "use",
        "view",
        "vkern"
    ];

    /**
     * This method automatically loads and creates DOM nodes.
     *
     * The symtax for the object is as follows;
     * - the tag property gives the object's tag name
     * - the ns property gives the object's namespace. Optional, defaults to the
     *   SVG namespace.
     * - the children property is a set of sub-objects with the same syntax.
     *
     * @param p_desc the object describing the element to create and initialize.
     * @param p_oInsertBefore Optional. the child before which the loaded content
     *        should be inserted
     * @return the element that was created.
     */
    sw.loadContent = function (p_desc, p_oInsertBefore) {
        var content;

        if (typeof p_desc === "string") {
            content = document.createTextNode(p_desc);
            this.appendChild(document.createTextNode(p_desc));
        } else if (typeof p_desc === "object") {
            // Save the reserved values first.
            var tagOrig = p_desc.tag;
            var nsOrig = p_desc.ns;
            var childrenOrig = p_desc.children;

            // Now, process the element.
            var tag = p_desc.tag;

            if (tag === undefined) {
                throw new Error(
                            "the element description requires a 'tag' property");
            }

            var ns = sw.svgNS;

            if (p_desc.ns !== undefined) {
                ns = p_desc.ns;
            }

            content = document.createElementNS(ns, tag);

            if (content === null || content === undefined) {
                throw new Error("was not able to create an element with tag " +
                                     tag + " in namespace " + ns);
            }

            var children = p_desc.children;

            delete p_desc.children;
            delete p_desc.tag;
            delete p_desc.ns;

            content.setAttributes(p_desc);

            if (children !== undefined && children !== null) {
                var nChildren = children.length;
                if (typeof nChildren === "number") {
                    for (var i = 0; i < nChildren; i++) {
                        var c = content.loadContent(children[i]);
                    }
                }
            }

            // Restore
            p_desc.children = childrenOrig;
            p_desc.tag = tagOrig;
            p_desc.ns = nsOrig;

            if (p_oInsertBefore === undefined) {
                p_oInsertBefore = null;
            }

            if (this.insertBefore !== undefined) {
                this.insertBefore(content, p_oInsertBefore);
            }
            sw.initIds(content);
        } else {
            throw new Error("loadContent requires an object or string parameter");
        }

        return content;
    }

    /**
    * The setAttributes method to be installed on all element classes.
    *
    * @param attributes an object with the attributes to set on the object this
    *        method is called on.
    */
    sw.setAttributes = function (attributes) {
        var value,
            ns = null,
            nsPrefix,
            nsIndex;

        for (var p in attributes) {
            if (attributes.hasOwnProperty(p) === true) {
                nsIndex = p.indexOf(":");
                if (nsIndex !== -1) {
                    nsPrefix = p.substring(0, nsIndex);
                    ns = this.lookupNamespaceURI(nsPrefix);
                    if (ns === null) {
                        // No namespace declaration was found on the node.
                        // This may be because the node is not in the tree
                        // yet. The best thing which can be done here is to
                        // check if we can find the namespace definition on the
                        // document element.
                        ns = document.documentElement.lookupNamespaceURI(nsPrefix);

                        // If the namespace is still not found, check the
                        // default list of known namespaces
                        if (defaultNamespacePrefixes[nsPrefix] !== undefined) {
                            ns = defaultNamespacePrefixes[nsPrefix];
                        }
                    }
                } else {
                    ns = null;
                }
                value = attributes[p];
                try {
                    this.setAttributeNS(ns, p, value);
                } catch (e) {
                    console.log("could not set " + p + " for " + ns + " to " + value);
                }
            }
        }
    };

    /**
     * Get a number of attributes on this element and return them in an object.
     *
     * @param attr1, ... attrN a variable length list of attributes to retrieve
     *        from this element.
     * @return an object whose properties are the requested attribute values
     */
    sw.getAttributes = function () {
        var result = {};
        var nsIndex = -1;
        var attribute;
        var ns = null;
        var nsPrefix;

        for (var i = 0; i < arguments.length; i++) {
            attribute = arguments[i];
            nsIndex = attribute.indexOf(":");
            if (nsIndex !== -1) {
                nsPrefix = attribute.substring(0, nsIndex);
                ns = this.lookupNamespaceURI(nsPrefix);
                if (ns === null) {
                    ns = svg.lookupNamespaceURI(nsPrefix);
                }
            } else {
                ns = null;
            }
            result[attribute] = this.getAttributeNS(ns, attribute);
        }

        return result;
    }

    /**
     * Utility to get the bounds of an object in the nearest viewport space.
     */
    sw.getViewportBBox = function () {
        var bbox = this.getBBox();
        var vBbox = null;
        var viewport = this.nearestViewportElement;
        var ctm = this.getTransformToElement(viewport);
        if (bbox !== null) {
            // This is one of the short-comings of SVG: there is no way to get
            // the bbox in the desired coordinate space. So we have to transform
            // the bounds and compute the box from that, which leads to
            // boxes which might be larger than needed (e.g., where there are
            // rotations). However, for common cases, this is doing the job.
            var points = [
                {x: bbox.x, y: bbox.y},
                {x: bbox.x + bbox.width, y: bbox.y},
                {x: bbox.x, y: bbox.y + bbox.height},
                {x: bbox.x + bbox.width, y: bbox.y + bbox.height}
            ];

            var tPoints = [
                {}, {}, {}, {}
            ];

            for (var i = 0; i < 4; i++) {
                ctm.transformPoint(points[i], tPoints[i]);
            }

            var minX = tPoints[0].x;
            var minY = tPoints[0].y;
            var maxX = tPoints[0].x;
            var maxY = tPoints[0].y;

            for (i = 1; i < 4; i++) {
                if (tPoints[i].x < minX) {
                    minX = tPoints[i].x;
                } else if (tPoints[i].x > maxX) {
                    maxX = tPoints[i].x;
                }

                if (tPoints[i].y < minY) {
                    minY = tPoints[i].y;
                } else if (tPoints[i].y > maxY) {
                    maxY = tPoints[i].y;
                }
            }

            vBbox = {
                x: minX,
                y: minY,
                width: maxX - minX,
                height: maxY - minY
            };
        }
        return vBbox;
    };

    /**
     * Transforms a point.
     *
     * @param p_pt an object with x/y properties
     * @param p_oResult an object where the transformed point is stored
     * @return the result
     */
    sw.transformPoint = function (p_pt, p_oResult) {
        var result = p_oResult;
        if (p_oResult === undefined) {
            result = {};
        }

        result.x = this.a * p_pt.x + this.c * p_pt.y + this.e;
        result.y = this.b * p_pt.x + this.d * p_pt.y + this.f;

        return result;
    };

    /**
     * Sets the matrix to identity
     */
    sw.toIdentity = function () {
        this.a = 1;
        this.b = 0;
        this.c = 0;
        this.d = 1;
        this.e = 0;
        this.f = 0;
        return this;
    };


    /**
    * Installs the setAttributes method on the prototype object which holds the
    * setAttribute (no 's') method.
    *
    * @param documentElement if undefined, defaults to document.documentElement,
    *        assuming an SVG root.
    * @param scope if undefined, defaults to the global scope.
    */
    sw.init = function (documentElement, scope) {
        if (documentElement === undefined) {
            documentElement = document.documentElement;
        }
        if (scope === undefined) {
            scope = window;
        }
        var errors = {};

        var hasErrors = false;

        for (var i = 0; i < sw.svgElements.length; i++) {
            var tag = sw.svgElements[i];
            var elt = document.createElementNS(sw.svgNS, tag);
            if (elt !== null && elt !== undefined) {
                var proto = elt.constructor.prototype;
                if (proto.setAttributes === undefined) {
                    proto.setAttributes = sw.setAttributes;
                }
                if (proto.getAttributes === undefined) {
                    proto.getAttributes = sw.getAttributes;
                }
                if (proto.loadContent === undefined) {
                    proto.loadContent = sw.loadContent;
                }
                if (proto.firstElmeent === undefined) {
                    proto.firstElement = sw.firstElement;
                }
                if (proto.nextElement === undefined) {
                    proto.nextElement = sw.nextElement;
                }
                if (proto.prevElement === undefined) {
                    proto.prevElement= sw.prevElement;
                }
                if (proto.removeAllChildren === undefined) {
                    proto.removeAllChildren = sw.removeAllChildren;
                }
                if (proto.getMatrix === undefined) {
                    proto.getMatrix = sw.getMatrix;
                }
                if (proto.setMatrix === undefined) {
                    proto.setMatrix = sw.setMatrix;
                }
                if (proto.getViewportBBox === undefined) {
                    proto.getViewportBBox = sw.getViewportBBox;
                }
                if (proto.getHideHandler === undefined) {
                    proto.getHideHandler = sw.getHideHandler;
                }
                if (proto.getShowHandler === undefined) {
                    proto.getShowHandler = sw.getShowHandler;
                }
            } else {
                errors[tag] = "Constructed element was " + elt;
                hasErrors = true;
            }
        }

        // Hook a transformPoint and toIdentity on SVGMatrix
        var svg = documentElement;
        var isSVG = true;
        if (svg.nodeName !== "svg") {
            svg = document.createElementNS(sw.svgNS, "svg");
            isSVG = false;
        }

        var m = svg.createSVGMatrix();
        if (m.constructor.prototype.transformPoint === undefined) {
            m.constructor.prototype.transformPoint = sw.transformPoint;
        }
        if (m.constructor.prototype.toIdentity === undefined) {
            m.constructor.prototype.toIdentity = sw.toIdentity;
        }

        if (hasErrors === true) {
           throw new Error("Could not install setAttributes on all elements");
        }

        document.constructor.prototype.loadContent = sw.loadContent;

        sw.initIds(documentElement);

        // Make the root 'svg' element available in the global scope
        if (isSVG) {
            scope.svg = documentElement;
        }
    }

    /**
     * Processes ids on elements and sets a variable of that name on their parents.
     *
     * @param elt the element to process. Its children are processed recursively.
     */
    sw.initIds = function (elt) {
        var id = elt.id;
        if (id !== undefined &&
            id !== null &&
            id !== "" &&
            (typeof id === "string") &&
            elt.parentNode !== undefined &&
            elt.parentNode !== null &&
            elt.parentNode[id] === undefined) {
            sw.addElementShortHand(id, elt, elt.parentNode);
        }

        var c = elt.firstChild;
        while (c !== null) {
            if (c.nodeType === Node.ELEMENT_NODE) {
                sw.initIds(c);
            }
            c = c.nextSibling;
        }
    }

    /**
     * Adds a property of the name "id" to the parent chain, starting with the
     * parent parameter. If the parent itself has an id, then the property is set
     * on that node. Otherwise, the property is set on the first ancestor with an
     * id
     *
     * @param id the name of the property to set
     * @param node the value of the property to set
     * @param parent the first candidate parent on which the property might be set
     */
    sw.addElementShortHand = function(id, node, parent) {
        // Note that parent.id is the value of the 'id' attribute on parent
        // whereas parent[id] is the value of the property with the name of the
        // id parameter (e.g., 'myRect') on parent.
        if (parent.id !== undefined && parent.id !== "") {
            if (parent[id] === undefined) {
                parent[id] = node;
            }
        } else if (parent.parentNode !== null && parent.parentNode !== parent) {
            sw.addElementShortHand(id, node, parent.parentNode);
        } else {
            if (document[id] === undefined) {
                document[id] = node;
            }
        }
    }


    /**
     * Helper method to find out if an element is a descendant of a given parent
     * node.
     *
     * @param candidate the element that may be the descendant of the parent.
     * @param parent the parent under which the candidate may be
     */
    sw.isDescendantOf = function (candidate, parent) {
        var isDescendant = false;
        var p = candidate;

        while (p !== parent && p.parentNode !== null) {
            p = p.parentNode;
        }

        return (p === parent);
    }

    /**
     * Helper method: converts a <code>String</code> to an <code>Element</code>
     * and throws an error if the element cannot be found. If the parameter is
     * not a string, it is returned as is.
     */
    sw.stringToElement = function (p_element) {
        var element = p_element;

        if (typeof p_element === "string") {
            element = document.getElementById(p_element);
        }

        if (element === null) {
            throw new Error ("Could not find element with id " + p_element);
        }

        return element;
    }
})();