TOC

学习 SVG:简单拖动

<!doctype html>
<html lang="en" xmlns="https://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <title></title>
  </head>
  <body style="width:1000px;margin:10px auto;">
    <svg
      id="example"
      width="1000"
      height="800"
      xmlns="https://www.w3.org/2000/svg"
    >
      <!-- 画个框框当边界 -->
      <rect
        x="0"
        y="0"
        width="100%"
        height="100%"
        fill="none"
        stroke="rgb(99,99,99)"
        stroke-width="2"
      />

      <circle
        id="circle1"
        class="dragable"
        cx="100"
        cy="100"
        r="30"
        fill="red"
        fill-opacity="0.7"
      />
      <circle
        id="circle2"
        class="dragable"
        cx="200"
        cy="100"
        r="30"
        fill="yellow"
        fill-opacity="0.7"
      />
      <circle
        id="circle3"
        class="dragable"
        cx="300"
        cy="100"
        r="30"
        fill="blue"
        fill-opacity="0.7"
      />
    </svg>
  </body>
  <script>
    var svg = document.getElementById("example"),
      target = null,
      startPoint = svg.createSVGPoint(),
      curPoint = svg.createSVGPoint();
    function refreshPoint(event) {
      curPoint.x = event.clientX;
      curPoint.y = event.clientY;
    }
    var dragables = document.getElementsByClassName("dragable");
    for (var i = 0; i < dragables.length; i++) {
      var dragable = dragables[i];
      dragable.addEventListener("mousedown", function (event) {
        target = event.target;
        refreshPoint(event);
        var matrix = target.getCTM();
        startPoint.x = curPoint.x - matrix.e;
        startPoint.y = curPoint.y - matrix.f;
      });
    }
    svg.addEventListener("mousemove", function (event) {
      if (!target) return;
      refreshPoint(event);
      var newX = curPoint.x - startPoint.x;
      var newY = curPoint.y - startPoint.y;
      target.setAttributeNS(
        null,
        "transform",
        "translate(" + newX + "," + newY + ")",
      );
    });
    svg.addEventListener("mouseup", function (event) {
      if (!target) return;
      target = null;
    });
  </script>
</html>