【问题标题】:Uniquely Identify KineticJS Shape唯一标识 KineticJS 形状
【发布时间】:2014-02-15 06:07:09
【问题描述】:

我有一个循环来查看给定形状是否与 KineticJS 程序中的任何其他形状发生碰撞。下面是这种情况的伪代码

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;
}

我不喜欢这种方法的地方在于,我必须将每个形状的索引保存在代码中的某个位置。此外,如果我从数组中删除元素,代码将会中断。

我阅读了文档,找不到任何关于比较形状等的信息,但我可能忽略了一些东西。 KineticJS 是否已经有了唯一识别/比较形状实例的方法?如果不是,是否可以将自定义数据附加到节点?它仍然可以与序列化一起使用吗?这样做是否会破坏当前或未来版本的 KineticJS?

编辑:明确地说,这是我正在考虑的解决方案

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;
}

【问题讨论】:

    标签: javascript kineticjs


    【解决方案1】:

    是的。

    您可以为任何动力学节点(形状、文本等)分配一个唯一的 ID:

    var shape123 = new Kinetic.Circle({
        id:(nextShapeId),
        ...
    

    您可以像这样获取任何节点的 id:

    anyNode.getId();
    

    您可以要求舞台为您提供对该节点的引用,如下所示:

    // 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];
    

    【讨论】:

    • *Derp*。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2012-06-06
    • 2012-11-25
    相关资源
    最近更新 更多