使用javascript移动后,SVG路径保持不变

时间:2016-10-20 20:18:06

标签: javascript svg svg-animate

我的SVG中有一个矩形,我有一个像飞机一样的图形,我想使用蒙版并在随机轨道上移动它。我正在为此寻找溶剂。enter image description here

编辑: 我想得到一个javascript,它像黑色路径一样在SVG中作为掩码。想要移动并制作元素的副本。

这是我的svg我想移动飞机并在移动后复制:

<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" height="500px" viewBox="0 0 500 500" width="500px" version="1.1" y="0px" x="0px" xmlns:xlink="http://www.w3.org/1999/xlink" enable-background="new 0 0 500 500">
<g id="_x32_">
    <path d="M250.2,59.002c11.001,0,20.176,9.165,20.176,20.777v122.24l171.12,95.954v42.779l-171.12-49.501v89.227l40.337,29.946v35.446l-60.52-20.18-60.502,20.166v-35.45l40.341-29.946v-89.227l-171.14,49.51v-42.779l171.14-95.954v-122.24c0-11.612,9.15-20.777,20.16-20.777z"/>
    <path stroke="#000" stroke-width="0.2" d="M31.356,500.29c-17.26,0-31.256-13.995-31.256-31.261v-437.67c0-17.265,13.996-31.261,31.256-31.261h437.68c17.266,0,31.261,13.996,31.261,31.263v437.67c0,17.266-13.995,31.261-31.261,31.261h-437.67z" fill="none"/>
</g>
</svg>

1 个答案:

答案 0 :(得分:1)

我不确定我到底知道你想要什么。但这里有一个小小的演示,希望至少可以帮助你开始。

// Get references to the various elements in the SVG
var svg = document.getElementById("Layer_1");
var blackpath = svg.getElementById("blackpath");
var redplane = svg.getElementById("redplane");

// Add an event listener to the SVG that captures mouse move events
svg.addEventListener("mousemove", function(evt) {
  // Convert the mouse position from screen coords to SVG coords.
  var pt = svg.createSVGPoint();
  pt.x = evt.clientX;
  pt.y = evt.clientY;
  pt = pt.matrixTransform(svg.getScreenCTM().inverse());

  // Move the red plane to the mouse mosition
  redplane.setAttribute("x", pt.x);
  redplane.setAttribute("y", pt.y);

  // Create a <use> element to add a cloned "copy" of the plane to the "blackpath" group.
  var useElement = document.createElementNS("http://www.w3.org/2000/svg", "use");
  useElement.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#plane");
  // Position the clone at the mouse coords
  useElement.setAttribute("x", pt.x);
  useElement.setAttribute("y", pt.y);
  // Add it to the blackpath group
  blackpath.appendChild(useElement);
});
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" height="500px" viewBox="0 0 500 500" width="500px" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <path id="plane" 
          d="M250.2,59.002c11.001,0,20.176,9.165,20.176,20.777v122.24l171.12,95.954v42.779l-171.12-49.501v89.227l40.337,29.946v35.446l-60.52-20.18-60.502,20.166v-35.45l40.341-29.946v-89.227l-171.14,49.51v-42.779l171.14-95.954v-122.24c0-11.612,9.15-20.777,20.16-20.777z" transform="scale(0.2, 0.2) translate(-250, -250)"/>
  </defs>
  <rect width="500" height="500" fill="#407085"/>
  <g id="blackpath" fill="black"></g>
  <use id="redplane" xlink:href="#plane" fill="#f30000" x="-100" y="-100"/>  
</svg>