Moving a Group of SVG Elements on Mouse Click

耗尽温柔 提交于 2019-12-11 10:40:15

问题


I'm trying to move a group of circles when a user clicks one of them. The group only moves once on the first click, but not afterwards. Here's the sample code I'm using:

function move_circle(e)     
{
var grp = e.target.parentNode;
grp.setAttribute("transform", "translate(" + 50 + ", " + 50 + ")");
}

<g onclick="move_circle(evt)">
  <circle cx="150" cy="100" r="25" fill="red"  />
  <circle cx="170" cy="120" r="5" fill="red"  />
</g>

回答1:


Every time that you click a circle, the event handler is setting the transform attribute of the g element to "translate(50, 50)". I believe what you intended to do is to repeat the translation every time a circle was clicked. In other words, you want to compose the translation with the one that is already applied to the element. Like so:

function move_circle(e) {
  var g = e.target.parentNode,
      t;

  if (g.transform.baseVal.numberOfItems == 0) {
    g.setAttribute("transform", "translate(" + 50 + ", " + 50 + ")");
  } else {
    t  = g.transform.baseVal.getItem(0),
    t.setMatrix(t.matrix.translate(50, 50));
  }
}

If no transformation has been applied, it will apply the translation as you were previously doing. If a transformation's already being applied to the element, then you use the existing transformation matrix, apply another translation to it, and then set the result of that to the transformation matrix of the element. (The translate() operation does not mutate the matrix. It returns a copy of the matrix with the operation applied to it. Thus, you have to update the transformation with that new matrix.)



来源:https://stackoverflow.com/questions/14036107/moving-a-group-of-svg-elements-on-mouse-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!