使用javascript设置svg组的中心点

问题描述 投票:2回答:1

在一个游戏中,我目前正在制作一个由节点构建的地图,当你点击它们时,你正在向不同的节点扭曲。我当前的地图看起来像那样(用two.js创建它是一个svg组,其中每个圆和行是svg路径元素,例如:

<path transform="matrix(1 0 0 1 553 120)" d="M 8 0 C 8 2.02 7.085 4.228 5.656 5.656 C 4.228 7.085 2.02 8 0 8 C -2.021 8 -4.229 7.085 -5.657 5.656 C -7.086 4.228 -8 2.02 -8 0 C -8 -2.021 -7.086 -4.229 -5.657 -5.657 C -4.229 -7.086 -2.021 -8 -0.001 -8 C 2.02 -8 4.228 -7.086 5.656 -5.657 C 7.085 -4.229 8 -2.021 8 0 Z " fill="#003251" stroke="#ebebeb" stroke-width="1" stroke-opacity="1" fill-opacity="1" visibility="visible" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="4" id="19"></path>

地图看起来像:game map

标记为红色的节点是您在区域/地图上当前位置的指示器。如何重新定位svg组,使当前玩家位置始终位于容器的中心,将整个地图移动到左/右/上/下,并变为:enter image description here enter image description here

使用以下函数,我可以更改svg组的x,y坐标:

function shiftMap(id_attr, offsetX, offsetY) {
    let elem = $(id_attr);
    if (elem) {
        let params = ' translate(' + offsetX + ',' + offsetY + ')';
        elem.attr('transform', params);
    }
}

我还有一个功能来检测当前玩家位置节点坐标,所以我试着这样做:

//where playerPosX = X of the current player node location (red mark)
//and playerPosY = Y of the current player node location (red mark)
shiftMap("svgMapID", playerPosX, playerPosY);

不幸的是,这个位置并不准确,并且地图移位/移动到处,离开容器边界等等。任何帮助都非常感谢。谢谢!

提示:有可能通过twojs锚点来做,但我不知道如何。更多信息:https://two.js.org/#two-anchor

javascript svg position two.js
1个回答
1
投票

您必须计算svg-group的边界框并移动该组,考虑组本身的外部偏移和相对于中心节点的内部偏移。

enter image description here

假设您希望这个新的随机节点位于您的组的中心,以红色突出显示。

然后你计算它与容器有关的XY。让我们说X = 400Y = 200

然后计算与容器相关的所有地图组的边界框。

在这个例子中,Y1可能是0,你必须找到X1。尝试使用group.getBoundingClientRect(shallow)中描述的Two.js docs。假设'X1 = 300','Y1 = 0'。

让你的容器W(宽度)= 1000和H(高度)= 700,让我们计算你的最终坐标:

finalX= (W/2) - (X + X1) = 500 - 700 =-200

finalY= (H/2) - (Y + Y1) = 350 - 200 =150

这意味着你必须通过-200(左边200)和X(150到底部)移动地图组150

© www.soinside.com 2019 - 2024. All rights reserved.