在鼠标单击上移动一组SVG元素 [英] Moving a Group of SVG Elements on Mouse Click

查看:194
本文介绍了在鼠标单击上移动一组SVG元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击其中一个圈子时,我正在尝试移动一组圈子。该组仅在第一次单击时移动一次,但之后不移动。这是我正在使用的示例代码,

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>


推荐答案

每次单击一个圆圈时,事件处理程序将 g 元素的转换属性设置为translate(50,50) 。我相信你打算做的是每次点击一个圆圈时重复翻译。换句话说,您希望使用已应用于元素的转换来组合转换。像这样:

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));
  }
}

如果没有应用任何转换,它将应用像以前一样翻译。如果已经将变换应用于元素,则使用现有的变换矩阵,对其应用另一个转换,然后将其结果设置为元素的变换矩阵。 ( translate()操作不会改变矩阵。它会返回矩阵的副本并应用操作。因此,您必须使用新的更新转换矩阵。)

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

这篇关于在鼠标单击上移动一组SVG元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆