Search code examples
javascriptcreatejseaseljs

Remove a shape on click with CreateJS


How do you remove only the shape that's in CreateJS? For my example, I have created a few squares with a function called createSquare. My goal is to have a function, or a click event, that removes only the square that is clicked.

I have tried event listeners and on click, and have had no luck. I have commented out the code that I tried to use.

Here is a link to a working fiddle.

JS is as follows:

var canvas;
var stage;
var square;

function init() {   
    canvas = document.getElementById("canvas");
    stage = new createjs.Stage(canvas);
}

function createSquare(){
    square = new createjs.Shape();
    square.graphics.beginFill("red").drawRect(0, 0, 50, 50)
    square.x = Math.random() * canvas.width;
        square.y = Math.random() * canvas.height;
    stage.addChild(square);
    stage.update();
}

// This code should remove the squares
/*
square.on("click", function(evt) {
    stage.removeChild(this);
});
*/

window.onload = init();

createSquare();
createSquare();
createSquare();
createSquare();
createSquare();
createSquare();

Solution

  • Event handlers in CreateJS are passed an event object. Mouse events receive a MouseEvent.

    The target of the event will be what was clicked on.

    square.on("click", function(evt) {
        stage.removeChild(evt.target);
        stage.update();
    });
    

    You will need to add the listener to each square when it is created.

    Alternatively, you could listen to the stage one time.

    stage.on("click", function(evt) {
        stage.removeChild(evt.target);
        stage.update();
    });