Friday, 12 September 2014

Draggable container in EaselJS

I needed to create a dragging container in EaselJS whereby all objects in the container are moved by the mouse.

I found a solution online and it suggested creating a rectangle shape the size of the stage and adding ‘mousedown’ and ‘mousemove’ events to the shape. The only problem with this solution is that the container child objects will not be clickable because the draggable rectangle shape is covering the clickable objects.

To overcome this issue I decided not to use the rectangle shape, but to add ‘stagemousedown’ and ‘stagemousemove’ events onto the stage. This way the container child objects will still be clickable as well as draggable.

Here is the example code below, and an live example can be seen here.

<!doctype html>
        html,body{padding:0; margin:0;}
        #canvas{background-color: #000000;} 
    <script src="easeljs.js"></script>
    <body onload="init()">
    <canvas id="canvas" width="800" height="600"></canvas>
    var stage, containerDrag, dragOffset;
    function init(){
        //setup stage
        stage = new createjs.Stage('canvas');
        createjs.Ticker.addEventListener("tick", tick);
        //drag container
        containerDrag = new createjs.Container();
        //stage listeners 
        stage.addEventListener("stagemousedown", startDrag);   
        stage.addEventListener("stagemouseup", stopDrag); 
        dragOffset = new createjs.Point();

        //add random shapes to container
        for(var i = 0; i < 100; i++){
            var rect = new createjs.Shape();
  '#ff0000').drawRect(0,0,getRandom(10, 30), getRandom(10, 30));
            rect.x = getRandom(0, stage.canvas.width);
            rect.y = getRandom(0, stage.canvas.height);
    //draggable listeners
    function startDrag(){
        dragOffset.x = stage.mouseX - containerDrag.x;
        dragOffset.y = stage.mouseY - containerDrag.y;
        stage.addEventListener("stagemousemove", moveDrag);   
    function stopDrag(){
         stage.removeEventListener("stagemousemove", moveDrag);   
    function moveDrag(e){
      containerDrag.x = e.stageX - dragOffset.x;
      containerDrag.y = e.stageY - dragOffset.y;
    //random utility function    
    function getRandom(min, max){
        return min + (Math.random() * (max-min));
    function tick(e){


  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP