Question

I would like to add an event listener to my image object so that when clicked it destroys itself but it doesn't seem to do anything.

var tshirtS = new Image();
tshirtS.onload = function () {
    var tshirtSk = new Kinetic.Image({
        image: tshirtS,
        width: 50,
        height: 58,
        listening: true
    });

    tshirtS.on('click', function() {
        tshirtS.destroy();
  });

    // add the image to the layer
    layer2.add(tshirtSk);
    typeOptions.add(tshirtSk);

    stage.add(layer2);
    typeOptions.draw();
    return tshirtSk;
};
tshirtS.src = 'tshirt-small.png';
Was it helpful?

Solution

A couple of glitches in your code:

  • tshirtSk is the object you should assign the click event to

  • after you destroy the tshirtSk, you must redraw the layer to un-display tshirtSk

Fixed code:

// not tshirtS.on('click',function(){

tshirtSk.on('click', function() {
    tshirtSk.destroy();
    layer2.draw();
});

Good luck with your project!

A Demo: http://jsfiddle.net/m1erickson/DcjnF/

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Prototype</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>

<style>
body{padding:20px;}
#container{
  border:solid 1px #ccc;
  margin-top: 10px;
  width:350px;
  height:350px;
}
</style>        
<script>
$(function(){

    var stage = new Kinetic.Stage({
        container: 'container',
        width: 350,
        height: 350
    });
    var layer2 = new Kinetic.Layer();
    stage.add(layer2);

    var tshirtS = new Image();
    tshirtS.onload = function () {
        var tshirtSk = new Kinetic.Image({
            image: tshirtS,
            width: 50,
            height: 58,
            listening: true
        });
        //
        tshirtSk.on('click', function() {
            tshirtSk.destroy();
            layer2.draw();
        });
        // add the image to the layer
        layer2.add(tshirtSk);
        layer2.draw();
        return tshirtSk;
    };
    tshirtS.src = 'https://dl.dropboxusercontent.com/u/139992952/multple/T-Shirt_blue.png';


}); // end $(function(){});

</script>       
</head>

<body>
    <h4>Click to destroy the T-shirt.</h4>
    <div id="container"></div>
</body>
</html>

[ Addition: add image on stage click ]

You can listen for clicks on tshirtSk and add a new image like this:

tshirtSk.on('click', function (event) {
    layer2.add(new Kinetic.Image({image:yourOtherImage}));
    layer2.draw();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top