SVG小组翻译问题

时间:2011-11-02 12:57:44

标签: drag-and-drop svg translation 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>

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

1 个答案:

答案 0 :(得分:5)

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

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

(dx, dy)

我们已向组elememt添加了两个属性:<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> $x来存储元素的当前位置(或者到目前为止所有移动的累积增量,具体取决于您的外观在它)。它们在定义了ID为“BC”的元素之后的脚本中初始化为零。它们在$y中更新,并在moveIt()中使用。由于我们从startMove()中的($x, $y)中减去了新的增量(x1, y1),因此这些新的增量会在startMove()中稍后有效地添加到(dx, dy)。这样可以确保moveIt()说明到目前为止的所有移动以及当前移动。