javascript 移动后 SVG 路径保持不变

SVG paths stays after moving with javascript

我的 SVG 中有一个矩形,我有一个像飞机一样的图形,我想使用蒙版并将其移动到随机轨道上。我正在寻找解决方案。

编辑: 我想得到一个 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>

我不确定我是否完全理解您想要什么。但这里有一个小演示,希望至少能帮助您入门。

// 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>