问题描述
我正在尝试向图像添加点击事件( Kinetic.Image
)我正在添加到KineticJS阶段。
I am trying to add a click event to an image (Kinetic.Image
) I am adding to a KineticJS stage.
- 当我使用简单的层次结构时,如下所示(测试0),可以成功触发事件。
- 但是,当在更复杂的层次结构中添加图像时(测试1),事件不会被触发。
我创建了一个,演示两种等级情况。
I have created a Fiddle that demonstrates both hierarchy situations.
// The canvas container for the stage
var container = $("#container").html("");
// Create the stage
var stage = new Kinetic.Stage({
container: container.attr("id"),
width: container.width(),
height: container.height()
});
// Load image
var img = new Image();
img.onload = function() {
// Dimensions of the image
var w = this.width;
var h = this.height;
// The base layer
var baseLayer = new Kinetic.Layer({
width: w,
height: h
});
// The group
var group = new Kinetic.Group();
// The asset layer
var assetLayer = new Kinetic.Layer({
width: w,
height: h
});
// The kinetic image element
var element = new Kinetic.Image({
image: this,
width: w,
height: h
});
// Event when image is clicked
element.on("click", function() { alert("Image clicked"); });
// Build hierarchy
assetLayer.add(element);
group.add(assetLayer);
baseLayer.add(group);
stage.add(baseLayer);
// Draw the stage
stage.draw();
}
// Load image from URL
img.src = "http://www.html5canvastutorials.com/demos/assets/lion.png";
我认为这可能与事件冒泡有关,并试图改变收听
图层上的属性,但不幸的是,这没有任何区别。任何建议将不胜感激。
I thought it maybe was related to event bubbling, and tried altering the listening
property on the layer, but unfortunately this made no difference. Any advice would be greatly appreciated.
推荐答案
我有一种感觉你不能分组 Kinetic.Layer
,仅 Kinetic.Shape
。请参阅本教程中的措辞:
I have a feeling you can't group Kinetic.Layer
, only Kinetic.Shape
. See the wording at this tutorial: http://www.html5canvastutorials.com/kineticjs/html5-canvas-complex-shapes-using-groups-with-kineticjs/
我改变了2行小提琴,我让它工作:
I changed 2 lines in your fiddle and I got it to work:
替换:
assetLayer.add(element);
group.add(assetLayer);
使用:
//assetLayer.add(element);
group.add(element);
瞧!警报会触发图像上的点击。
Voila! The alert fires for 'click' on image.
这篇关于KineticJS事件未针对分组图层的子项触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!