free transform example

by Emre

HTML

<div id="workspace"></div>

CSS

#workspace { width: 1000px; height: 1000px; }

JavaScript

/*
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

Raphael.fn.freeTransform = function(subject, options, callback) {
    // Enable method chaining
    if ( subject.freeTransform ) return subject.freeTransform;

    // Add Array.map if the browser doesn't support it
    if ( !( 'map' in Array.prototype ) ) {
        Array.prototype.map = function(callback, arg) {
            var mapped = new Array();

            for ( var i in this ) {
                if ( this.hasOwnProperty(i) ) {
                    mapped[i] = callback.call(arg, this[i], i, this);
                }
            }

            return mapped;
        };
    }

    var paper = this;

    var ft = subject.freeTransform = {
        axes: [ 'x', 'y'],
        callback: ( typeof callback == 'function' ? callback : false ),
        items: subject.type == 'set' ? subject.items : [ subject ],
        handles: false,
        opts: {
            attrs: {
                fill: '#000',
                stroke: '#000'
                },
            boundary: {
                x: paper._left ? paper._left : 0,
                y: paper._top  ? paper._top  : 0,
                width: paper.width,
                height: paper.height
                },
            drag: true,
            grid: false,
            gridSnap: 0,
            keepRatio: false,
            rotate: true,
            rotateSnap: false,
            scale: true,
            size: 1.2, 
            showBBox: false,
            },
        // Keep track of transformations in case we can't access item._.transform
        transform: {
            rotate: 0,
            scale:     { x: 1, y: 1 },
            translate: { x: 0, y: 0 }
           }
        };

    // Override defaults
    for ( var i in options ) {
        subject.freeTransform.opts[i] = options[i];
    }

    // Nothing to do here
    if ( !ft.opts.rotate && !ft.opts.scale && !ft.opts.drag ) {
        return ft;
    }

    if (...