Skip to content Skip to sidebar Skip to footer

How To Remove Bitmap Image On Click From Canvas

I am using createjs as my framework. I've placed a Bitmap on the canvas and I created a function to try and remove it but I keep getting an error message in the console that image

Solution 1:

Make image as global variable, so that it can be accessed by all the functions in your case function pop.

var image;// defining 'image' variable as globalfunction init(){

    var canvas = new createjs.Stage("canvas");

   // Add image to canvas
   image = new createjs.Bitmap("image.png");
   image.x = 200;
   image.y = 180;
   image.scaleX = 0.35;
   image.scaleY = 0.35;
   canvas.addChild(image);

   image.addEventListener('click', pop);

   canvas.update();

}

//remove image from canvasfunctionpop() {
  console.log('pop');
  canvas.removeChild(image);
}

Solution 2:

This is a scope issue. You defined image inside your init function, so it is not accessible on the pop method.

There are two easy fixes. Either move the var image outside of the init function, or use the click target instead.

var image;
function init() {
  init = new createjs.Bitmap();
  // etc
}

// ORfunction pop(event) {
  stage.removeChild(event.target);
}

Scope is really important to understand when building JavaScript applications, so I suggest getting to know it a little better :)

Cheers,

Post a Comment for "How To Remove Bitmap Image On Click From Canvas"