Moving a Group of SVG Elements on Mouse Click

2019-08-06 01:10发布

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条回答
贪生不怕死
2楼-- · 2019-08-06 01:43

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.)

查看更多
登录 后发表回答