简体   繁体   English

如何从画布上单击删除位图图像

[英]How to remove bitmap image on click from canvas

I am using createjs as my framework. 我正在使用createjs作为我的框架。 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. 当我单击它时,我收到控制台消息“ pop”,后跟上面提到的错误。 I've tried moving the function inside init but I appear to get the same problem. 我试过将函数移到init内,但似乎出现了同样的问题。

This is a scope issue. 这是一个范围问题。 You defined image inside your init function, so it is not accessible on the pop method. 您在init函数中定义了image ,因此无法通过pop方法访问它。

There are two easy fixes. 有两个简单的修复程序。 Either move the var image outside of the init function, or use the click target instead. var image移到init函数之外,或者使用click目标。

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 :) 在构建JavaScript应用程序时,了解范围非常重要,因此建议您更好地了解它:)

Cheers, 干杯,

Make image as global variable, so that it can be accessed by all the functions in your case function pop . 将image设置为全局变量,以便您的case函数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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM