SVG小组翻译问题

Ale*_*lex 3 svg translation drag-and-drop coordinates coordinate-transformation

我必须出于特定原因进行小组翻译(SVG).我不知道为什么我不能正确地做到这一点,因为在翻译完成后,在另一个单击组上它会重置开始位置的翻译并让我在SVG画布上乱跑.我在链接上写了准系统示例:http://www.atarado.com/en/stripboard-layout-software/group-translation-problem.svg,这里是代码:

<svg xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">
<script><![CDATA[
function startMove(evt){
 x1=evt.clientX;
 y1=evt.clientY;
 group=evt.target.parentNode;
 group.setAttribute("onmousemove","moveIt(evt)");
}
function moveIt(evt){
 dx=evt.clientX-x1;
 dy=evt.clientY-y1;
 group.setAttributeNS(null,"transform","translate("+ dx + ", " + dy +")");
}
function drop(){
 group.setAttributeNS(null, "onmousemove",null);
}
]]></script>
<rect x="0" y="0" width="100%" height="100%" fill="dodgerblue"/>

<g id="BC" transform="translate(0, 0)" onmousedown="startMove(evt)" onmouseup="drop()"><circle id="C" cx="60" cy="60" r="22" fill="lightgrey" stroke="black" stroke-width="8"/><circle id="B" cx="120" cy="60" r="22" fill="orange" stroke="black" stroke-width="8" /></g>
</svg>
Run Code Online (Sandbox Code Playgroud)

欢迎任何愿意提供帮助的人.

Ada*_*man 5

组在第二步中重置的原因是您将变换设置为平移,(dx, dy)其等于移动开始(x1, y1)位置与当前位置之间的差异(evt.clientX, evt.clientY).这意味着当您第二次单击并稍微移动鼠标时,则dx和dy是小数字.然后使用它们将变换设置为稍微偏离初始位置的变形.请记住,在任何时候应用于组的变换必须描述从组的初始位置的变换.

解决问题的一种方法是存储到目前为止应用于该组的所有移动的总增量,并使用此累积(dx, dy)来构建变换.例如:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<script><![CDATA[
function startMove(evt){
  group=evt.target.parentNode;
  x1=evt.clientX - group.$x;
  y1=evt.clientY - group.$y;
  group.setAttribute("onmousemove","moveIt(evt)");
}
function moveIt(evt){
  dx=evt.clientX-x1;
  dy=evt.clientY-y1;
  group.setAttributeNS(null,"transform","translate("+ dx + ", " + dy +")");
  group.$x = dx; 
  group.$y = dy; 
}
function drop(){
  group.setAttributeNS(null, "onmousemove",null);
}
]]></script>
<rect x="0" y="0" width="100%" height="100%" fill="dodgerblue"/>
<g id="BC" transform="translate(0, 0)" onmousedown="startMove(evt)" onmouseup="drop()">
  <circle id="C" cx="60" cy="60" r="22" fill="lightgrey" stroke="black" stroke-width="8"/>
  <circle id="B" cx="120" cy="60" r="22" fill="orange" stroke="black" stroke-width="8" />
</g>
<script><![CDATA[
var group=document.getElementById("BC");
group.$x = 0;
group.$y = 0;
]]></script>
</svg>
Run Code Online (Sandbox Code Playgroud)

我们已经为组elememt添加了两个属性:$x$y存储元素的当前位置(或者到目前为止所有移动的累积增量,具体取决于您查看它的方式).它们在定义了ID为"BC"的元素之后的脚本中初始化为零.它们被更新moveIt()和消费startMove().由于我们减去我们的新的增量($x, $y)来自(x1, y1)startMove(),这些新的增量有效地被添加到(dx, dy)在后面moveIt().这确保(dx, dy)了到目前为止所有移动以及当前移动的帐户.