Two.JS: '执行失败'removecchild '& # 39;节点# 39;当试图删除从

Two.JS : 'Failed to execute 'removeChild' on 'Node' when trying to remove shapes interpreted from SVG

本文关键字:节点 删除 removecchild JS 执行 失败 Two      更新时间:2023-09-26

我使用Two.JS将使用Two.JS解释方法从SVG中解释的形状渲染到舞台。

这些添加了一个寿命属性,在Two的渲染循环中,我检查插图,如果时间到了就删除它。

这是工作的大多数时间(>99%),但偶尔形状卡住,我得到这个错误:

Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node':要删除的节点不是此节点的子节点。

showIllustration: (which) =>
    alreadyIllustration = false
    for shape, i in @_shapes
        if shape.isIllustration is true
            alreadyIllustration = true
    if alreadyIllustration is false
        switch which
            when 'food'
                if Math.random() > 0.49
                    id = 'currywurst'
                else
                    id = 'pretzel'
            when 'mascot'
                if Math.random() > 0.49
                    id = 'ample'
                else
                    id = 'bear'
            when 'landmark'
                if Math.random() > 0.49
                    id = 'tower'
                else
                    id = 'tor'
        illustration = @_two.interpret document.getElementById id
        illustration.center().translation.set @_two.width / 2, @_two.height / 2
        @_foreGround.add illustration
        illustration.lifeSpan = 100
        illustration.creationTime = new Date().getTime()
        illustration.isIllustration = true
        @_shapes.push illustration

,这里是我的循环来删除插图:

removeShapes: () =>
    time = new Date().getTime()
    for shape, i in @_shapes by -1
        if shape.lifeSpan
            if time - shape.creationTime >= shape.lifeSpan
                shape.remove()
                @_shapes.splice i, 1

这里是发生错误的two.js的相关代码。

removeChild: function(id) {
        var elem = this.domElement.querySelector('#' + id);
        if (elem) {
          this.elem.removeChild(elem);
        }
      },

这只发生在解释svg上,而不是形状上。形状和解释形状都返回2。多边形对象,所以这看起来很奇怪。

我能想到的一件事是,two.js使用元素的id,它解释为多边形的id,如果有两个元素具有相同的id,那么这将导致一个错误,当试图删除。但是,如果存在任何插图,那么每次停止添加插图时,alreadyIllustration检查似乎都能正确工作。

我还尝试将id设置为它创建的时间,而不是元素的id,因此每次都是唯一的,但这会导致其他问题和错误。

许多谢谢。

这并不是一个完整的修复,但我发现这个问题与窗口上的模糊/褪色事件有关,以及Chrome处理这个问题的方式。当窗口不在焦点中时,错误似乎发生了,并且当前显示的相同插图被触发。

插图从数组中删除,但直到窗口重新聚焦后才从DOM中删除,这意味着检查将通过,并且显示具有相同ID的相同插图的多个实例。

为了防止问题发生,我在窗口不在焦点时禁用了事件,因此在窗口恢复焦点之前不会显示新的插图。