Raphael JS Demo

Raphael JS demo for rectangle, arrow and moving rect objects.

by JQ Purfect

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//code.jquery.com/jquery-1.4.3.min.js"></script>
 <input id="arrow" value="Arrow" type="button"/>
    <input id="rect" value="Rect" type="button"/>
    <input id="del" value="Delete Rect" type="button"/>
    <input id="clr" value="Clear All" type="button"/>
    <input id="unbind" value="UnBind" type="button"/>

    <div class="paper" id="svg_paper" style="background-image:url(http://www.psdgraphics.com/file/colorful-triangles-background.jpg);"/>

CSS

.paper {
            margin: 5px auto;
            width: 800px;
            height: 600px;
            position: absolute;
            border: outset 1px #000;
            cursor: crosshair;
            z-index: -1;
        }

JavaScript

$(function () {
            var mouseDownX = 0;
            var mouseDownY = 0;
            var elemClicked;
            var rect;
            var arrow;

            var paper = Raphael("svg_paper", 800, 600);

    // Draw Arrow
            function DrawArrow(x, y) {
                var element = paper.path("M" + x + " " + y);
                element.attr({
    // stroke: Raphael.getColor(),
                    stroke: "yellow",
                    "stroke-width": 4,
                    "arrow-end": "classic-medium-medium"
                });
                return element;
            }

    // Draw Rect
            function DrawRectangle(x, y, w, h) {

                var element = paper.rect(x, y, w, h);
                element.attr({
                    fill: "gray",
                    opacity: .5,
                    stroke: "#F00"
                });                                
                
                $(element.node).attr('id', 'rct' + x + y);
                console.log(element.attr('x') + " - " + element.attr('y'));                
                
                element.drag(move, start, up);                

                element.click(function (e) {
                    elemClicked = $(element.node).attr('id');
                });

                return element;                

            }
    


    // Start, move, and up are the drag functions
            start = function () {
    // storing original coordinates
                this.ox = this.attr("x");
                this.oy = this.attr("y");
                this.attr({
                    opacity: 1
                });
                if (this.attr("y") < 60 && this.attr("x") < 60) this.attr({
                    fill: "#f2f2f2"
                });
            }, move = function (dx, dy) {               

    // Move will be called with dx and dy
                if (this.attr("y") > 600 || this.attr("x") > 800) this.attr({
                    x: this.ox + dx,
                 ...