Home

Algorithmic Advent: 11 – Raphaël JS demo

Published on 11 Dec 2010. Tagged with javascript, algorithmicadvent.

Raphaël is a JavaScript vector drawing library that uses SVG and VML to render its object tree. Thanks to VML, the library even supports Internet Explorer 6.0. There are some great demos of Raphaël's capabilities on the project's homepage.

I had some fun with it a few weeks ago. Here's the result. It's nothing special but it might give you an idea on how to work with Raphaël.

You might want to take a look into the official documentation to fully comprehend what's going on. But please keep in mind that this is mere messing around than writing good code.

<!DOCTYPE html>

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>New</title>

        <!-- Available at http://raphaeljs.com/ -->
        <script type="text/javascript" src="./raphael-min.js"></script>

        <script type="text/javascript">

        window.onload = function () {

            createBox = function (paper, label) {
                var rect   = paper.rect(0, 0, 80, 20),
                    rectbb = rect.getBBox(),
                    text   = paper.text(0, 0, label),
                    group  = null;

                rect.attr({fill: '#eee'});
                text.translate(rectbb.width / 2, rectbb.height / 2);

                group = paper.set();
                group.push(rect);
                group.push(text);

                group.mouseover(function () {
                    rect.attr({fill: '#fcc'});
                });

                group.mouseout(function () {
                    rect.attr({fill: '#eee'});
                });

                group.attr({cursor: 'pointer'});

                return group;
            };

            connect = function(paper, obj1, obj2) {
                var obj1bb    = obj1.getBBox(),
                    obj2bb    = obj2.getBBox(),
                    path      = '',
                    connector = null;

                path = "M " + (obj1bb.x + obj1bb.width / 2) + " "
                       + (obj1bb.y + obj1bb.height / 2)
                       + "L " + (obj2bb.x + obj2bb.width / 2) + " "
                       + (obj2bb.y + obj2bb.height / 2);

                connector = paper.path(path);
                connector.toBack();
                return connector;
            };

            var paper = Raphael(0, 0, 400, 400),
                box1  = createBox(paper, "Hello World!"),
                box2  = createBox(paper, "A Test"),
                box3  = createBox(paper, "Another Test");

            box1.translate(Math.random() * 350, Math.random() * 380);
            box2.translate(Math.random() * 350, Math.random() * 380);
            box3.translate(Math.random() * 350, Math.random() * 380);

            connect(paper, box1, box2);
            connect(paper, box2, box3);
        };

        </script>
    </head>

    <body>

    </body>

</html>