[英]Uniquely Identify KineticJS Shape
I have a loop to see if a given shape collides with any other in a KineticJS program. 我有一个循环来查看给定的形状是否与KineticJS程序中的任何其他形状发生冲突。 Below is pseudocode for the situation
下面是这种情况的伪代码
function hasCollision(shape, index) {
var children = layer.children;
for(var i = 0, l = children.length; i < l; i++) {
if(i === index) continue; // Only check other shapes
if(collision(shape, children[i]))
return true;
}
return false;
}
What I don't like about this approach is that I have to save the index for each shape somewhere in my code. 我对这种方法不满意的是,我必须将每种形状的索引保存在代码中。 Additionally, the code will break if I remove elements from the array.
此外,如果我从数组中删除元素,代码也会中断。
I read the documentation and couldn't find anything about comparing shapes etc., but I might have overlooked something. 我阅读了文档,找不到关于比较形状等的任何信息,但是我可能忽略了一些东西。 Does KineticJS already have a way to uniquely identify/compare instance of shapes?
KineticJS是否已经具有一种唯一标识/比较形状实例的方法? If not, is it OK to append custom data to a Node?
如果不是,可以将自定义数据附加到节点上吗? Will it still work with serialization?
它仍然可以与序列化一起使用吗? Is doing this likely to break things with current or future versions of KineticJS?
这样做可能会破坏当前或将来版本的KineticJS吗?
EDIT : To be clear, this is the solution I'm considering 编辑 :明确地说,这是我正在考虑的解决方案
shape.uid = uid_factory++;
...
function hasCollision(shape) {
var children = layer.children;
for(var i = 0, l = children.length; i < l; i++) {
var other = children[i];
if(other.uid === shape.uid) continue; // Only check other shapes
if(collision(shape, other))
return true;
}
return false;
}
Yes. 是。
You can assign a unique id to any Kinetic Node (shape, text, etc): 您可以为任何动力学节点(形状,文本等)分配唯一的ID:
var shape123 = new Kinetic.Circle({
id:(nextShapeId),
...
And you can get any node's id like this: 您可以像这样获取任何节点的ID:
anyNode.getId();
And you can ask the stage to get you a reference to that node like this: 您可以要求阶段为您提供对该节点的引用,如下所示:
// use stage.find to fetch all nodes with an id == theId
var nodes = stage.find("#"+theId);
// nodes is a collection, so grab the first element
var myNode = nodes[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.