How to remove bitmap image on click from canvas

陌路散爱 提交于 2020-01-06 06:18:09

问题


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 is not defined. This is what my code looks like:

// onload=init() called in html doc
function 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 canvas
function pop() {
console.log('pop');
canvas.removeChild(image);
}

When I click on it, I get the console message "pop" followed by the error I mentioned above. I've tried moving the function inside init but I appear to get the same problem.


回答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 global
 function 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 canvas
function pop() {
  console.log('pop');
  canvas.removeChild(image);
}



回答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
}

// OR

function 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,



来源:https://stackoverflow.com/questions/48173143/how-to-remove-bitmap-image-on-click-from-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!