Javascript 移动到没有 JS 库的 SVG 路径

Javascript to Move SVG path without JS library

本文关键字:库的 SVG 路径 JS 移动 Javascript      更新时间:2023-09-26

我想在SVG画布上拖动路径。要求是不使用任何JS库。任何例子都会对我有所帮助。

我知道拉斐尔.js这很容易。

谢谢。

下面是纯 JS 中的一个示例:

<svg id='mysvg' height="800" width="800">
    <path id='mypath' fill="#4444ff" stroke="#000000" d="M100,300L400,300L100,0Z" transform=""></path>
</svg>

.JS:

el=document.getElementById("mypath");
sv=document.getElementById("mysvg");
flag=false; //to check if the mouse is currently down?
sv.onmousedown=function(e){
    flag=true;
    x1=e.clientX;
    y1=e.clientY;
    var t=el.getAttribute('transform');
    if(t){
      var parts  = /translate'('s*([^'s,)]+)[ ,]([^'s,)]+)/.exec(t);
      var firstX = parts[1], firstY = parts[2];
      x1=x1-firstX*1;
      y1=y1-firstY*1;
    }
    /* x1 and y1 now contain the previous position*/
};
sv.onmousemove=function(e){
    if(flag){
        x=e.clientX;
        y=e.clientY;
        t="translate("+(x-x1)+","+(y-y1)+")"
        el.setAttribute('transform',t);
    }
};
sv.onmouseup=function(){flag=false};

小提琴:http://jsfiddle.net/gF8Wd/2/