左右移动SVG组

时间:2016-12-16 12:41:59

标签: javascript animation svg

我有一个显示“时间轴”的片段。线(SVG组)应根据鼠标移动向左或向右移动。控制台显示要使用的数据,但我不知道如何移动g#node-line

这是粗略的结构:

svg#svg
  g#node-line
    line#line
    g#nodes
      line.node
      line.node
      line.node
      line.node
      ...

现在代码:

  var ns = "http://www.w3.org/2000/svg";
  var svg = document.createElementNS(ns, "svg");
  svg.setAttribute("id", "svg");  
  svg.setAttribute("width", "800px");
  svg.setAttribute("height", "450px");

  var line = document.createElementNS(ns, "line");
  line.setAttribute("id", "line");
  line.setAttribute("stroke", "white");
  line.setAttribute("stroke-width", "10px");
  line.setAttribute("x1", "0");
  line.setAttribute("y1", 225);
  line.setAttribute("x2", "800");
  line.setAttribute("y2", 225);

  var nodes = document.createElementNS(ns, "g");
  nodes.setAttribute("id", "nodes");

  for (var i = 0; i < 100; i++) {

    var node = document.createElementNS(ns, "line");
    node.setAttribute("class", "node");
    node.setAttribute("stroke", "white");
    node.setAttribute("stroke-width", "2px");
    node.setAttribute("x1", i * 40 );
    node.setAttribute("y1", 225);
    node.setAttribute("x2", i * 40 );
    node.setAttribute("y2", 225 - 12);

    nodes.appendChild(node);

  }

  var nodeLine = document.createElementNS(ns, "g");
  nodeLine.setAttribute("id", "node-line");

  nodeLine.appendChild(line);
  nodeLine.appendChild(nodes);

  svg.appendChild(nodeLine);

  var container = document.getElementById('container');
  container.appendChild(svg);

  document.getElementById('svg').addEventListener('mousemove', function(e) {
    var boundaries = svg.getBoundingClientRect()
    var offset = e.clientX - boundaries.left;
    if (offset < 400) {
      var distanceFromCenter = 400 - offset;
      console.log('left: ' + distanceFromCenter);
    }
    if (offset > 400) {
      var distanceFromCenter = offset - 400;
      console.log('right: ' + distanceFromCenter);
    }
  });
html, body {
  height: 100%;
}
body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
#container {
  background-color: orange;  
}
<div id="container"></div>

非常感谢。

1 个答案:

答案 0 :(得分:2)

设置群组的transform属性。

e.g。 transform="translate(30,0)"向右移动30个单位或transform="translate(-30,0)"移动30个单位。