我想在我的图像对象中添加一个事件监听器,这样当点击它时它会自行销毁,但它似乎没有做任何事情。
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';
答案 0 :(得分:1)
代码中的一些小问题:
tshirtSk是您应将点击事件分配给
销毁tshirtSk后,必须重新绘制图层以取消显示tshirtSk
固定代码:
// not tshirtS.on('click',function(){
tshirtSk.on('click', function() {
tshirtSk.destroy();
layer2.draw();
});
祝你的项目好运!
演示: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>
[添加:在舞台上点击添加图片]
您可以收听tshirtSk上的点击并添加如下新图片:
tshirtSk.on('click', function (event) {
layer2.add(new Kinetic.Image({image:yourOtherImage}));
layer2.draw();
});