Skip to content Skip to sidebar Skip to footer

SVG Paths Stays After Moving With Javascript

I have a rectangle in my SVG, I have one graphic like aircraft and i would like to use mask and move it on random orbit. I'm looking for the sollution for this. EDIT: I would like

Solution 1:

I'm not sure I understand exactly what you want. But here is a little demo that hopefully should help you get started at least.

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

Post a Comment for "SVG Paths Stays After Moving With Javascript"