css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              
<div id="loading">Loading...</div>

<main>
  <div id="controls">

    <div>
      Click to add point<br>
      Drag to move<br>
      Right-click to remove
    </div>
    <hr>

    <label>
      <input id="closed" type="checkbox" />
      Close Path
    </label>
    <br><br>    
    <label>
      <input id="show-path" type="checkbox" checked />
      Show Path
    </label>
    <br><br>
    
    <label>
      <input id="scale" type="checkbox" />
      Scale Rope
    </label>
    <br><br>
    <label>
      <input id="rope" type="checkbox" checked />
      Show Rope
    </label>
    
    <hr>

    <button id="clear">Clear</button>
  </div>

  <canvas id="pixi-stage"></canvas>
  <svg id="stage">

    <defs>    
      <g class="handle">      
        <rect class="handle-space" width="32" height="32" x="-16" y="-16" />
        <circle class="handle-outer" r="0" />
        <circle class="handle-inner" r="3.5" />      
      </g>

      <g class="path-group">
        <path class="spiro"></path>
        <g class="handles"></g>
      </g>    
    </defs>

    <g id="shape-group">
      <rect id="shape" x="0" y="0" width="60" height="60" style="visibility:hidden"/>
    </g>
  </svg>
</main>


            
          
!
            
              $r: 10;

html, body {
  height: 100%;
}

body {    
  background: #000;  
  color: white;
  overflow: hidden;
}

button {
  color: black;
}

main {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  visibility: hidden;
}

hr {
  border-color: #222;
  margin: 15px 0;
}

#loading {
  padding: 10px;
  position: absolute;
}

#controls {
  position: absolute;
  z-index: 10;  
  top: 25px;
  left: 25px;
  font-size: 13px;
  border: 1px solid #222;
  border-width: 0 1px 1px 0;
  width: 150px;
  padding: 15px;
  top: 0;
  left: 0;  
  background: rgba(0,0,0,0.5);
}

canvas {
  
}

#pixi-stage {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

svg {
  position: absolute;
  top: 0;
  left: 0;  
  width: 100%;
  height: 100%;
}

.spiro {
  fill: none;
  stroke-width: 2;
}

#shape {
  width: 60px;
  height: 60px;
  stroke: red;
  x: 0;
  y: 0;
  fill: #aaa;   
  visibility: hidden;
}

.point-bounds {
  fill: green;
  fill-opacity: 0.3;
  stroke: green;
}

.point-inner {
  fill: red;
}

.point-outer {
  fill: blue;
  fill-opacity: 0.3; 
  stroke-width: 1;  
  stroke: blue;
}

//delete
.handle-shape {
  fill: transparent;
  stroke: transparent;
}

.handle-space {
  fill: transparent;
  stroke: transparent;
}

.handle-outer {
  stroke: #333;
  stroke-width: 1;
  fill: yellow;
  fill-opacity: 0.6;
  fill: cornflowerblue;  
  stroke: transparent;
}

.handle-inner {
  stroke: #333; 
  fill: #dadada;  
  fill: cyan;
}

.handle-dragger {
  fill: transparent;  
  stroke: transparent;  
  stroke: purple;
}









            
          
!
            
              

// Old and outdated version
// Created: 08/21/15

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
console.clear();
var log = console.log.bind(console);
var perf = window.performance;
var now = perf ? perf.now.bind(perf) : Date.now;
function timeCallback(callback) {
    var start = now();
    callback();
    return now() - start;
}
function timeLimit(limit) {
    var start = now();
    return function () { return now() - start >= limit; };
}
function bindScope(scope) {
    for (var m in scope) {
        if (typeof scope[m] === "function" && scope[m].bind) {
            scope[m] = scope[m].bind(scope);
        }
    }
}
_.mixin({ timeCallback: timeCallback, timeLimit: timeLimit, bindScope: bindScope });
var $ = function (query, context) {
    if (context === void 0) { context = document; }
    return context.querySelector(query);
};
var $$ = function (query, context) {
    if (context === void 0) { context = document; }
    return _.toArray(context.querySelectorAll(query));
};
var svgns = "http://www.w3.org/2000/svg";
var baseURL = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/";
var create = document.createElementNS.bind(document, svgns);
var loader = new PIXI.loaders.Loader(baseURL);
loader
    .add("rope", "rope2.png")
    .load(function () { return new App(); });
//
// TEMP
// ===========================================================================
var width = window.innerWidth;
var height = window.innerHeight;
var starCache = 400;
var starSize = 25;
function createTexture() {
    var radius1 = starSize / 2;
    var radius2 = radius1 / 2;
    var center = radius1;
    var points = 5;
    var canvas = document.createElement("canvas");
    canvas.width = starSize;
    canvas.height = starSize;
    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(radius1, 0);
    for (var i = 0; i < points * 2; i++) {
        var radius = i % 2 ? radius2 : radius1;
        var x = center + radius * Math.sin(i * Math.PI / points);
        var y = center - radius * Math.cos(i * Math.PI / points);
        ctx.lineTo(x, y);
    }
    ctx.closePath();
    ctx.fillStyle = "#ffffff";
    ctx.fill();
    var texture = PIXI.Texture.fromCanvas(canvas);
    PIXI.Texture.addTextureToCache(texture, "star");
}
createTexture();
//
// STAR
// ===========================================================================
var Star = (function (_super) {
    __extends(Star, _super);
    function Star(scope, config) {
        _super.call(this, PIXI.Texture.fromFrame("star"));
        this.scope = scope;
        this.config = config;
        this.anchor.set(0.5);
        this.pivot.set(0.5);
        this.hide();
    }
    Object.defineProperty(Star.prototype, "size", {
        get: function () { return this.scale.x; },
        set: function (val) { this.scale.set(val); },
        enumerable: true,
        configurable: true
    });
    Star.prototype.animate = function (x, y, tint) {
        var _this = this;
        this.position.set(x, y);
        this.tint = tint;
        this.size = 0.2;
        this.show();
        var move = this.config.move;
        var time = this.config.time;
        var size = this.config.size;
        x += _.random(-move, move);
        y += _.random(-move, move);
        TweenLite.to(this, time, {
            x: x, y: y, size: size, alpha: 0,
            onComplete: function () {
                _this.hide();
                _this.scope.stars.push(_this);
            }
        });
    };
    Star.prototype.hide = function () {
        this.renderable = false;
        this.visible = false;
        this.alpha = 0;
        return this;
    };
    Star.prototype.show = function () {
        this.renderable = true;
        this.visible = true;
        this.alpha = 1;
        return this;
    };
    return Star;
})(PIXI.Sprite);
var getDist = function (p1, p2) {
    return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
};
//
// TILE ROPE
// ===========================================================================
var TileRope = (function (_super) {
    __extends(TileRope, _super);
    function TileRope(texture, points, tolerance) {
        if (points === void 0) { points = []; }
        if (tolerance === void 0) { tolerance = 7; }
        _super.call(this, texture, points);
        this.tolerance = tolerance;
        //_scale = 0.8;
        this._scale = 1;
        this.closed = false;
    }
    TileRope.prototype.clearMesh = function (points, total) {
        if (points === void 0) { points = []; }
        if (total === void 0) { total = points.length; }
        this.vertices = new Float32Array(total * 4);
        this.colors = new Float32Array(total * 2);
        this.indices = new Uint16Array(total * 2);
        this.uvs = new Float32Array(total * 4);
        this.points = points;
    };
    TileRope.prototype.render = function () {
        this.vertices = new Float32Array(this.points.length * 4);
        this.uvs = new Float32Array(this.points.length * 4);
        this.colors = new Float32Array(this.points.length * 2);
        this.indices = new Uint16Array(this.points.length * 2);
        this.refresh();
    };
    TileRope.prototype.updateTransform = function () {
        var points = this.points;
        if (points.length < 1) {
            return;
        }
        var lastPoint = points[0];
        var nextPoint;
        var perpX = 0;
        var perpY = 0;
        var vertices = this.vertices;
        var total = points.length, point, index, ratio, perpLength, num;
        var closed = (this.closed && total > 3);
        if (closed)
            lastPoint = points[total - 2];
        for (var i = 0; i < total; i++) {
            point = points[i];
            index = i * 4;
            if (i < points.length - 1) {
                nextPoint = points[i + 1];
            }
            else {
                if (closed)
                    nextPoint = points[1];
                else
                    nextPoint = point;
            }
            perpY = -(nextPoint.x - lastPoint.x);
            perpX = nextPoint.y - lastPoint.y;
            ratio = (1 - (i / (total - 1))) * 10;
            if (ratio > 1) {
                ratio = 1;
            }
            perpLength = Math.sqrt(perpX * perpX + perpY * perpY);
            num = this._texture.height / 2 * this._scale;
            perpX /= perpLength;
            perpY /= perpLength;
            perpX *= num;
            perpY *= num;
            vertices[index + 0] = point.x + perpX;
            vertices[index + 1] = point.y + perpY;
            vertices[index + 2] = point.x - perpX;
            vertices[index + 3] = point.y - perpY;
            lastPoint = point;
        }
        this.containerUpdateTransform();
    };
    TileRope.prototype.refresh = function () {
        var points = this.points;
        if (points.length < 1 || !this._texture._uvs) {
            return;
        }
        var uvs = this.uvs;
        var indices = this.indices;
        var colors = this.colors;
        //texturewidth
        var textureWidth = this._texture.width;
        uvs[0] = 0;
        uvs[1] = 0;
        uvs[2] = 0;
        uvs[3] = 1;
        colors[0] = 1;
        colors[1] = 1;
        indices[0] = 0;
        indices[1] = 1;
        var total = points.length, point, index, amount;
        var xOffset = 0;
        var prevPoint = points[0];
        for (var i = 1; i < total; i++) {
            point = points[i];
            index = i * 4;
            amount = i / (total - 1);
            var distx = points[i - 1].x - points[i].x;
            var disty = points[i - 1].y - points[i].y;
            var dist = Math.sqrt(distx * distx + disty * disty);
            var factor = dist / textureWidth / this._scale;
            xOffset += factor;
            uvs[index] = xOffset;
            uvs[index + 1] = 0;
            uvs[index + 2] = xOffset;
            uvs[index + 3] = 1;
            index = i * 2;
            colors[index] = 1;
            colors[index + 1] = 1;
            index = i * 2;
            indices[index] = index;
            indices[index + 1] = index + 1;
        }
        this.dirty = true;
    };
    return TileRope;
})(PIXI.mesh.Rope);
//
// ANIMATOR
// ===========================================================================
var Animator = (function () {
    function Animator(scope, motionPath, ropePath) {
        var _this = this;
        this.scope = scope;
        this.motionPath = motionPath;
        this.ropePath = ropePath;
        this.starCache = 800;
        this.pixiView = $("#pixi-stage");
        this.pathView = $("#stage");
        this.shape1 = $("#shape");
        this.shape2 = $("#shape"); //change  
        this.trans1 = this.shape1._gsTransform;
        this.trans2 = this.shape2._gsTransform;
        this.timeline = new TimelineMax({
            paused: true,
            onUpdate: this.render,
            onComplete: this.clearStage,
            callbackScope: this
        });
        this.renderer = PIXI.autoDetectRenderer(width, height, {
            view: this.pixiView,
            antialias: true,
            autoResize: true,
            //backgroundColor: 0xfafafa,
            backgroundColor: 0x000000,
        });
        this.particles1 = new PIXI.ParticleContainer(10000, {
            scale: true,
            position: true,
            rotation: true,
            uvs: true,
            alpha: true
        });
        this.speed = 700;
        //sprites = [];
        this.texture = PIXI.Texture.fromFrame("star");
        this.particles = new PIXI.Container();
        this.stage = new PIXI.Container();
        this.stars = [];
        // Good
        // [5, 0.5, 2]
        this.starAnim = {
            move: 10,
            time: 0.5,
            size: 2.3
        };
        this.proxy1 = { rotation: 0, x: 0, y: 0 };
        this.proxy2 = { rotation: 0, x: 0, y: 0 };
        this.showRope = true;
        this.filters = [];
        this.effects = {};
        var texture = loader.resources.rope.texture;
        var rope = new PIXI.Sprite(texture);
        rope.position.set(50, 200);
        this.rope = new TileRope(texture, [], 3);
        this.stage.addChild(this.rope);
        var shadow = new PIXI.filters.DropShadowFilter();
        this.effects.shadow = shadow;
        this.rope.filters = [shadow];
        shadow.alpha = 0.6;
        shadow.distance = 2;
        shadow.blur = 0.8;
        shadow.color = 0x000000;
        this.particles.renderable = false;
        this.stage.addChild(this.particles);
        this.createStars();
        TweenLite.ticker.addEventListener("tick", this.render, this);
        this.rope.path = this.ropePath;
        $("#rope").addEventListener("change", function (event) {
            _this.showRope = event.target.checked;
            var points = _this.showRope ? _this.motionPath.bezier.segs : [];
            if (_this.showRope)
                _this.rope.render(points);
            else
                _this.rope.clearMesh();
            motionPath.queueRender();
            _this.render();
        });
        this.ropePath.setRope(this.rope);
      
        events.on("path:update", function (points) {
            if (_this.showRope) {
                var _points = _this.ropePath.points;
                _this.rope.points = _points;
                _this.rope.render();
            }
            else {
                _this.rope.clearMesh();
            }
            _this.render();
        });
        events.on("stage:clear", function () {
            _this.rope.clearMesh();
            _this.render();
        });
      
        $("#scale").addEventListener("change", function (e) {
            //var _scale = this.rope._scale < 1 ? 1 : 0.5;
            var _scale = event.target.checked ? 0.5 : 1;
            TweenLite.to(_this.rope, 1.5, {
                _scale: _scale,
                onUpdate: function () {
                    _this.rope.render(_this.motionPath.bezier.segs);
                    _this.render();
                }
            });
        });
        $("#show-path").addEventListener("change", function (e) {
            //var _scale = this.rope._scale < 1 ? 1 : 0.5;
            var autoAlpha = event.target.checked ? 1 : 0;
            TweenLite.set(motionPath.path, { autoAlpha: autoAlpha });
        });
        this.render();
    }
    Animator.prototype.updateRope = function (points) {
        if (points === void 0) { points = []; }
        if (this.showRope) {
            this.rope.render(points);
        }
        else {
            this.rope.clearMesh();
        }
        this.render();
    };
    Object.defineProperty(Animator.prototype, "duration", {
        get: function () { return this.motionPath.length / this.speed; },
        enumerable: true,
        configurable: true
    });
    Animator.prototype.clearStage = function () {
        this.particles.renderable = false;
        this.render();
    };
    Animator.prototype.play = function () {
        TweenLite.set(this.shape1, { autoAlpha: 0 });
        this.particles.renderable = true;
        var tl = this.timeline;
        var dur = this.duration;
        var pad = this.starAnim.time + 1;
        var update1 = _.bind(this.updatePath, this, false);
        var update2 = _.bind(this.updatePath, this, true);
        _.assign(this.proxy1, this.motionPath.start);
        _.assign(this.proxy2, this.motionPath.end);
        var star1 = this.stars.shift();
        var star2 = this.stars.shift();
        star1.show();
        star2.show();
        TweenLite.set(star1, { alpha: 1, size: 0, x: this.proxy2.x, y: this.proxy2.y, tint: 0x99eeff });
        TweenLite.set(star2, { alpha: 1, size: 0, x: this.proxy1.x, y: this.proxy1.y, tint: 0xed1b24 });
        tl.clear()
            .to({}, 0.5, { onUpdate: update1 }, "enter")
            .to({}, 0.5, { onUpdate: update2 }, "enter")
            .to(this.shape1, dur, { bezier: this.motionPath, onUpdate: update1 }, "start")
            .to(this.proxy1, dur, { bezier: this.motionPath }, "start")
            .from(this.proxy2, dur, { bezier: this.motionPath, onUpdate: update2 }, "start")
            .to(star1, 0.5, { size: 0, alpha: 0 }, "end+=0.1")
            .to(star2, 0.5, { size: 0, alpha: 0 }, "end+=0.1")
            .play();
        return this;
    };
    Animator.prototype.updatePath = function (alt) {
        var _this = this;
        if (!this.stars.length) {
            console.warn("STAR CACHE IS EMPTY");
            return;
        }
        var tint1 = [0x99eeff, 0x3399cc, 0x5bb4cc, 0x2175d9, 0x00aedb, 0xa200ff];
        var tint2 = [0x880000, 0xed1b24, 0xff3232, 0xe30074, 0xd41243, 0xf47835];
        var tint3 = [0x448800, 0x7fcc7f, 0x00d27f, 0xb8d000, 0x8ec127, 0x006666];
        _.times(3, function () {
            var star = _this.stars.shift();
            var tint = alt ? tint2 : tint1;
            var x = alt ? _this.proxy2.x : _this.proxy1.x;
            var y = alt ? _this.proxy2.y : _this.proxy1.y;
            star && star.animate(x, y, _.sample(tint));
        });
        return this;
    };
    Animator.prototype.render = function () {
        this.renderer.render(this.stage);
    };
    Animator.prototype.createStars = function () {
        var i = this.starCache;
        while (i--) {
            var star = new Star(this, this.starAnim);
            this.particles.addChild(star);
            this.stars.push(star);
        }
        //log("STAR", this.stars[0]);
        return this;
    };
    return Animator;
})();
//
// TEMP MAIN
// ===========================================================================
var App = (function () {
    function App() {
        var _this = this;
        this.stage = $("#stage");
        this.shape = $("#shape");
        // TEMP
        TweenLite.set(this.shape, {
            xPercent: -50,
            yPercent: -50,
            transformOrigin: "center center"
        });
        this.motionPath = new MotionPath(this.stage, {});
        this.ropePath = this.motionPath.ropePath;
        this.animator = new Animator(this, this.motionPath, this.ropePath);
        // TEMP EVENTS... 
        $("#clear").addEventListener("click", function (event) {
            _this.motionPath.clear();
            events.fire("stage:clear");
        });
        $("#closed").addEventListener("change", function (event) {
            _this.motionPath.closed = event.target.checked;
        });
        window.addEventListener("resize", function () {
            _this.animator.renderer.resize(window.innerWidth, window.innerHeight);
            _this.animator.render();
        });
      
        TweenLite.set("#loading", { autoAlpha: 0 });
        TweenLite.to("main", 0.5, { autoAlpha: 1 });
    }
    App.prototype.resize = function () {
    };
    return App;
})();
//
// SPIRO CURVE
// ===========================================================================
var SpiroCurve = (function () {
    function SpiroCurve(path) {
        this.path = path;
        this.fits = true;
        this.bezier = {
            //TEMP
            _path: "",
            path: "",
            data: []
        };
    }
    SpiroCurve.prototype.solve = function (points, closed) {
        var step = 1;
        var size = this.path.size;
        var spline;
        for (var outer = 0; outer < 3; outer++) {
            spline = Spiro.setupSolver(points);
            if (outer === 2)
                break;
            try {
                for (var j = 0; j < 30; j++) {
                    if (Spiro.refineEuler(spline, step) < 1e-6)
                        break;
                }
                if (j < 30)
                    break;
            }
            catch (error) {
                console.warn("CANNOT FIT:", error);
            }
            step *= 0.5;
        }
        if (closed) {
            spline.segs = spline.segs.splice(size, size);
            spline.nodes = spline.nodes.splice(size, size);
        }
        this.path.fits = !outer;
        this.spline = spline;
        this.toBezier();
    };
    SpiroCurve.prototype.toBezier = function () {
        var segs = this.spline.segs;
        var start = this.path.start;
        this.bezier.path = "M" + [start.x, start.y];
        this.bezier.data = [start];
        // TEMP
        this.bezier._path = "M" + [start.x, start.y];
        this.bezier._path += "C";
        _.reduce(segs, function (bezier, seg) {
            var ths = seg.get_ths();
            var ks = Spiro.fitEuler(ths[0], ths[1]).ks;
            ks[2] = 0;
            ks[3] = 0;
            var data = Spiro.segToBezier(ks, seg.x1, seg.y1, seg.x2, seg.y2);
            _.forEach(data, function (points) {
                // TEMP
                bezier._path += points + ",";
                bezier.path += "C" + points;
                bezier.data.push(new Point(points[0], points[1]), new Point(points[2], points[3]), new Point(points[4], points[5]));
            });
            return bezier;
        }, this.bezier);
    };
    SpiroCurve.prototype.flatten = function () {
    };
    return SpiroCurve;
})();
//
// POINT
// ===========================================================================
var Point = (function () {
    function Point(x, y) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        this.x = x;
        this.y = y;
    }
    Point.from = function (point) {
        if (point === void 0) { point = null; }
        return new Point(point.x, point.y);
    };
    Point.lerp = function (point1, point2, amount) {
        return point1.clone().lerp(point2, amount);
    };
    Point.prototype.lerp = function (point, amount) {
        this.x = this.x * (1 - amount) + point.x * amount;
        this.y = this.y * (1 - amount) + point.y * amount;
        return this;
    };
    Object.defineProperty(Point.prototype, "xy", {
        get: function () { return { x: this.x, y: this.y }; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Point.prototype, "value", {
        get: function () { return { x: this.x, y: this.y }; },
        enumerable: true,
        configurable: true
    });
    Point.prototype.angleFrom = function (point) {
        return Math.atan2(this.y - point.y, this.x - point.x);
    };
    Point.prototype.angleTo = function (point) {
        return Math.atan2(point.y - this.y, point.x - this.x);
    };
    Point.prototype.clone = function () {
        return new Point(this.x, this.y);
    };
    Point.prototype.copy = function (point) {
        this.set(point.x, point.y);
        return this;
    };
    Point.prototype.mid = function (point) {
        var x = (this.x + point.x) / 2;
        var y = (this.y + point.y) / 2;
        return new Point(x, y);
    };
    Point.prototype.dist = function (point) {
        var dx = this.x - point.x;
        var dy = this.y - point.y;
        return Math.sqrt(dx * dx + dy * dy);
    };
    Point.prototype.equals = function (point) {
        return this.x === point.x && this.y === point.y;
    };
    Point.prototype.set = function (x, y) {
        if (x === void 0) { x = 0; }
        this.x = x;
        this.y = y || ((y !== 0) ? this.x : 0);
    };
    return Point;
})();
//
// ROPE PATH
// ===========================================================================
var RopePath = (function () {
    function RopePath() {
        this.tweenObj = {
            index: 0,
            x: 0,
            y: 0
        };
        this._fill1 = 0;
        this._fill2 = 1;
        this.points = [];
        this.nodes = [];
        this.segs = [];
        this.values = [];
        this.tolerance = 2;
        this.length = 0;
        this._offsets = [];
        this.offsets = [];
        this.targetIndex = 0;
        this.len = {
            fill: 0,
            path: 0,
            total: 0
        };
    }
    Object.defineProperty(RopePath.prototype, "fill1", {
        get: function () { return this._fill1; },
        set: function (val) {
            this._fill1 = val;
            this.updateFill();
        },
        enumerable: true,
        configurable: true
    });
    RopePath.prototype.resetFill = function () {
        this._fill1 = 0;
        this.tween.progress(0);
    };
    RopePath.prototype.updateFill = function () {
        var fill = this._fill1;
        this.tween.progress(this._fill1);
        var target = this.tweenObj;
        var points = this.points;
        var nodes = this.nodes;
        var len = this.len;
        var x = target.x;
        var y = target.y;
        var match = (target.index + 1) >> 0;
        var next = match + 1;
        this.targetIndex = match - 1;
        var diff = nodes[next].dist(target);
        match = match;
        len.fill = 0;
        this.offsets = _.reduce(this._offsets, function (result, offset, i) {
            if (i < match) {
                result.push(0);
            }
            else if (i === match) {
                result.push(diff);
                len.fill += diff;
            }
            else {
                result.push(offset);
                len.fill += offset;
            }
            return result;
        }, [0]);
        var offsets = this.offsets;
        var rope = this.rope;
        var textureWidth = rope._texture.width;
        var scale = rope._scale;
        var uvs = this.rope.uvs;
        var pL = this.len.path / textureWidth / scale;
        var fL = this.len.fill / textureWidth / scale;
        var offsetX = (pL - fL);
        for (var i = 0; i < this.points.length; i++) {
            if (i < match + 1) {
                var point = points[i];
                point.x = x;
                point.y = y;
            }
            var index = i * 4;
            var dist = offsets.length ? offsets.shift() : 0;
            var factor = dist / textureWidth / scale;
            offsetX += factor;
            uvs[index + 0] = offsetX;
            uvs[index + 2] = offsetX;
        }
        this.rope.dirty = true;
    };
    RopePath.prototype.setRope = function (rope) {
        this.rope = rope;
    };
    RopePath.prototype.setBezier = function (bezier) {
        this.bezier = bezier;
        this.length = 0;
        var total = bezier.length;
        var last = bezier[0];
        this._points = [last.clone()];
        this.nodes = [last.clone()];
        this.segs = [];
        this._offsets = [];
        this.offsets = [];
        this.len.fill = 0;
        this.len.path = 0;
        for (var i = 1; i < total;) {
            var p0 = last;
            var p1 = bezier[i++];
            var p2 = bezier[i++];
            var p3 = bezier[i++];
            this.flatten(p0, p1, p2, p3);
            last = p3;
        }
        this.addSegment(last.clone());
        this.mapValues();
    };
    RopePath.prototype.mapValues = function () {
        var _this = this;
        this.points = [];
        this.values = _.map(this.nodes, function (node, i) {
            var x = node.x;
            var y = node.y;
            _this.points.push({ x: x, y: y, index: i });
            return { x: x, y: y, index: i };
            ;
        });
        this.tween = new TimelineMax()
            .to(this.tweenObj, 1, { bezier: {
                values: this.values, curviness: 0
            }, ease: Power0.easeNone }, 0);
    };
    RopePath.prototype.addPoint = function (point) {
        var last = _.last(this._points);
        this.length += point.dist(last);
        this._points.push(point);
        this.points.push(point.clone());
    };
    RopePath.prototype.addSegment = function (node) {
        var nodes = this.nodes;
        var last = _.last(nodes);
        var size = _.size(nodes);
        this._offsets.push(node.dist(last));
        var segment = new Segment(last, node, size);
        nodes.push(node);
        this.segs.push(segment);
        this.length += segment.length;
        this.len.path += segment.length;
    };
    RopePath.prototype.flatten = function (p0, p1, p2, p3) {
        var pt1 = p0.mid(p1);
        var pt2 = p1.mid(p2);
        var pt3 = p2.mid(p3);
        var pt4 = pt1.mid(pt2);
        var pt5 = pt2.mid(pt3);
        var pt6 = pt4.mid(pt5);
        var a = p3.angleFrom(p0);
        var b = p1.angleFrom(p0);
        var c = p3.angleFrom(p2);
        var h1 = p0.dist(p1);
        var h2 = p3.dist(p2);
        var d1 = Math.abs(Math.sin(b - a) * h1);
        var d2 = Math.abs(Math.sin(c - a) * h2);
        var dmax = d1 > d2 ? d1 : d2;
        if (dmax > this.tolerance) {
            this.flatten(p0, pt1, pt4, pt6);
            this.addSegment(pt6.clone());
            this.flatten(pt6, pt5, pt3, p3);
        }
        else {
            this.addSegment(pt6.clone());
        }
    };
    return RopePath;
})();
//
// SEGMENT
// ===========================================================================
var Segment = (function () {
    function Segment(point1, point2, index) {
        this.point1 = point1;
        this.point2 = point2;
        this.index = index;
        this.length = this.point1.dist(this.point2);
    }
    Segment.prototype.update = function (last, total) {
        this.totalLength = total;
        this.startLength = last.endLength || 0;
        this.endLength = this.startLength + this.length;
        this.startFill = last.endFill || 0;
        this.endFill = this.endLength / total;
        return this;
    };
    return Segment;
})();
//
// MOTION PATH !!! PATH BUILDER
// ===========================================================================
var MotionPath = (function () {
    function MotionPath(parent, config) {
        this.parent = parent;
        this.group = $("defs > .path-group").cloneNode(true);
        this.path = $(".spiro", this.group);
        this.handles = $(".handles", this.group);
        this.type = "cubic";
        this.autoRotate = true;
        this.fits = false;
        this.queue = null;
        this.isActive = false;
        this.isDirty = false;
        this.points = [];
        this.bezier = {
            //////
            // Add to clear if keepin
            start: null,
            end: null,
            length: null,
            values: null,
            //////    
            path: "",
            segs: []
        };
        this.renderRope = true;
        this.tolerance = 7;
        this.startFill = 0;
        this.endFill = 0;
        this.ropePath = new RopePath();
        // Stop binding getters
        this.ready = false;
        // spiro added
        this.spiro = new SpiroCurve(this);
        this._closed = false;
        this._values = [];
        this.parent.appendChild(this.group);
        this.parent.addEventListener("mousedown", _.throttle(this.onPress.bind(this), 20));
        this.parent.addEventListener("contextmenu", function (e) {
            if (e.shiftKey)
                return;
            e.preventDefault();
        }, true);
        _.bindAll(this);
        this.ready = true;
    }
    Object.defineProperty(MotionPath.prototype, "closed", {
        get: function () { return this._closed; },
        set: function (flag) {
            this._closed = flag;
            this.indexPoints();
            this.queueRender();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "length", {
        get: function () { return this.ready ? this.path.getTotalLength() : null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "size", {
        // Change one of these
        get: function () { return this.ready ? this.points.length : null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "count", {
        get: function () { return this.ready ? this.points.length : null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "start", {
        get: function () { return this.ready ? Point.from(this.first) : null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "end", {
        get: function () { return this.ready ? Point.from(this.last) : null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "first", {
        get: function () { return _.first(this.points) || null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "last", {
        get: function () { return _.last(this.points) || null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(MotionPath.prototype, "values", {
        get: function () {
            if (!this.isDirty || this.count < 2)
                return this._values;
            this._values = _.flatten(this.bezier.segs).map(function (point) { return point.xy; });
            this.isDirty = false;
            return this._values;
        },
        enumerable: true,
        configurable: true
    });
    MotionPath.prototype.clear = function () {
        this.isDirty = false;
        _.forEach(this.points, function (point) { return point.remove(); });
        this.bezier.path = "";
        this.bezier.segs = [];
        this.points = [];
        this._values = [];
        this.path.setAttribute("d", "");
    };
    MotionPath.prototype.onPress = function (event) {
        event.preventDefault();
        var index = this.points.length;
        var point = new ControlPoint(this, this.handles, index, event);
        this.addPoint(point);
        point.start(event);
        return this;
    };
    MotionPath.prototype.setActive = function () {
        this.isActive = true;
        _.forEach(this.points, function (point) { return point.lock(); });
        return this;
    };
    MotionPath.prototype.clearActive = function () {
        this.isActive = false;
        _.forEach(this.points, function (point) { return point.unlock(); });
        return this;
    };
    MotionPath.prototype.queueRender = function () {
        if (this.queue)
            clearTimeout(this.queue);
        this.queue = _.defer(this.render);
        return this;
    };
    MotionPath.prototype.render = function () {
        var size = this.size;
        if (size < 2)
            return;
        this.isDirty = true;
        var closed = false;
        var points = _.map(this.points, function (pt) { return ({ x: pt.x, y: pt.y }); });
        if (this.closed && size > 3) {
            closed = true;
            points = points.concat(_.clone(points), _.clone(points));
        }
        this.spiro.solve(points, closed);
        this.ropePath.setBezier(this.spiro.bezier.data);
        events.fire("path:update", this.spiro.bezier.data);
        TweenLite.set(this.path, {
            stroke: this.fits ? 0xDADADA : 0xFF0000,
            strokeOpacity: 0.8,
            attr: { d: this.spiro.bezier.path }
        });
    };
    MotionPath.prototype.solve = function (points) {
        var spline, step = 1;
        for (var outer = 0; outer < 3; outer++) {
            spline = Spiro.setupSolver(points);
            if (outer === 2)
                break;
            try {
                for (var j = 0; j < 30; j++) {
                    if (Spiro.refineEuler(spline, step) < 1e-6)
                        break;
                }
                if (j < 30)
                    break;
            }
            catch (error) {
                console.warn("CANNOT FIT:", error);
            }
            step *= 0.5;
        }
        this.fits = !outer;
        return spline;
    };
    MotionPath.prototype.addPoint = function (point) {
        this.points.push(point);
        this.indexPoints();
        return this;
    };
    MotionPath.prototype.removePoint = function (point) {
        this.points.splice(point.index, 1);
        this.indexPoints();
        this.queueRender();
        return this;
    };
    MotionPath.prototype.indexPoints = function () {
        _.forEach(this.points, function (point, i) {
            point.index = i;
            point.startPoint = false;
            point.endPoint = false;
        });
        if (!this.closed || this.closed && this.count < 4) {
            this.last && (this.last.endPoint = true);
        }
        this.first && (this.first.startPoint = true);
        return this;
    };
    return MotionPath;
})();
//
// CONTROL POINT
// ===========================================================================
var ControlPoint = (function () {
    function ControlPoint(path, parent, index, event) {
        this.path = path;
        this.parent = parent;
        this.index = index;
        this.group = $("defs > .handle").cloneNode(true);
        this.space = $(".handle-space", this.group);
        this.inner = $(".handle-inner", this.group);
        this.outer = $(".handle-outer", this.group);
        this.hover = new TimelineLite({ paused: true });
        this.locked = false;
        this.inside = false;
        this.draggable = null;
        this._endPoint = false;
        this._startPoint = false;
        var x = event.pageX;
        var y = event.pageY;
        this.parent.appendChild(this.group);
        TweenLite.set(this.group, { x: x, y: y });
        this.hover.to(this.outer, 0.15, { attr: { r: 16 } });
        this.group.addEventListener("mouseenter", this.enter.bind(this));
        this.group.addEventListener("mouseleave", this.leave.bind(this));
        //log("ADD DRAGGABLE")
        this.draggable = new Draggable(this.group, {
            onPress: this.onPress,
            onDrag: this.onDrag,
            onRelease: this.onRelease,
            callbackScope: this,
            allowEventDefault: true
        });
    }
    Object.defineProperty(ControlPoint.prototype, "startPoint", {
        //#00FFFF
        get: function () { return this._startPoint; },
        set: function (flag) {
            this._startPoint = flag;
            var fill = flag ? 0xe30074 : 0x00FFFF;
            var r = flag ? 4.5 : 3.5;
            var strokeWidth = flag ? 1 : 1;
            TweenLite.set(this.inner, { fill: fill, strokeWidth: strokeWidth, attr: { r: r } });
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ControlPoint.prototype, "endPoint", {
        get: function () { return this._endPoint; },
        set: function (flag) {
            this._endPoint = flag;
            var fill = flag ? 0x2175d9 : 0x00FFFF;
            var r = flag ? 4.5 : 3.5;
            var strokeWidth = flag ? 1 : 1;
            TweenLite.set(this.inner, { fill: fill, strokeWidth: strokeWidth, attr: { r: r } });
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ControlPoint.prototype, "isDragging", {
        get: function () { return this.draggable && this.draggable.isDragging; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ControlPoint.prototype, "isPressed", {
        get: function () { return this.draggable && this.draggable.isPressed; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ControlPoint.prototype, "x", {
        get: function () { return this.group && this.group._gsTransform.x; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ControlPoint.prototype, "y", {
        get: function () { return this.group && this.group._gsTransform.y; },
        enumerable: true,
        configurable: true
    });
    ControlPoint.prototype.lock = function () {
        this.locked = true;
        this.isPressed ? this.hover.play() : this.hover.reverse();
    };
    ControlPoint.prototype.unlock = function () {
        this.locked = false;
        this.inside ? this.hover.play() : this.hover.reverse();
    };
    ControlPoint.prototype.enter = function (event) {
        this.inside = true;
        if (this.locked)
            return;
        this.hover.play();
        return this;
    };
    ControlPoint.prototype.leave = function (event) {
        this.inside = false;
        if (this.locked)
            return;
        this.hover.reverse();
        return this;
    };
    ControlPoint.prototype.start = function (event) {
        this.path.setActive();
        this.draggable.startDrag(event);
        this.onDrag(event);
        return this;
    };
    ControlPoint.prototype.onPress = function (event) {
        event.stopPropagation();
        event.preventDefault();
        if (event.ctrlKey || event.which === 3) {
            this.remove();
            this.path.removePoint(this);
        }
        else {
            this.path.setActive();
        }
        return this;
    };
    ControlPoint.prototype.onRelease = function (event) {
        this.path.clearActive();
    };
    ControlPoint.prototype.remove = function () {
        this.draggable.kill();
        this.parent.removeChild(this.group);
    };
    ControlPoint.prototype.onDrag = function (event) {
        event.stopPropagation();
        event.preventDefault();
        this.path.queueRender();
    };
    return ControlPoint;
})();
//
// EVENT AGGREGATOR
// ===========================================================================
var EventAggregator = (function () {
    function EventAggregator() {
        this.eventLookup = {};
    }
    EventAggregator.prototype.off = function (event, callback) {
        var listeners = this.eventLookup[event];
        if (event === "*")
            this.eventLookup = {};
        else if (!callback)
            this.eventLookup[event] = [];
        else
            _.remove(listeners, { callback: callback });
    };
    EventAggregator.prototype.on = function (event, callback, scope) {
        var listeners = this.eventLookup[event];
        if (!listeners)
            this.eventLookup[event] = listeners = [];
        listeners.push({ callback: callback, scope: scope });
        return function () { return _.remove(listeners, { callback: callback }); };
    };
    EventAggregator.prototype.once = function (event, callback, scope) {
        var _this = this;
        var on = function () {
            var data = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                data[_i - 0] = arguments[_i];
            }
            _this.off(event, on);
            callback.apply(scope, data);
        };
        return this.on(event, on);
    };
    EventAggregator.prototype.fire = function (event) {
        var data = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            data[_i - 1] = arguments[_i];
        }
        var listeners = this.eventLookup[event];
        if (!listeners)
            return;
        listeners.forEach(function (list) {
            try {
                return list.callback.apply(list.scope, data);
            }
            catch (error) {
                return _.isError(error) ? error : new Error(error);
            }
        });
    };
    return EventAggregator;
})();
var events = new EventAggregator();

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console