SVG相机平移每次都保持重置为0

SVG Camera Pan - Translate keeps resetting to 0 evertime?

本文关键字:相机 SVG      更新时间:2023-09-26

我有这个SVG画布元素,到目前为止,我已经到了这样一个地步,一旦用户点击并拖动画布,画布就会移动,屏幕外的元素就会变成屏幕上的元素等等…

然而,我有一个问题,当用户再次点击并拖动时,翻译单词重置为0,这使画布跳回到0,0。

这是我为那些不想使用JS fiddle 的人准备的代码

这是JSfiddle演示-https://jsfiddle.net/2cu2jvbp/2/

编辑:找到了解决方案-这是一个JSfiddle演示https://jsfiddle.net/hsqnzh5w/

任何建议都会很有帮助。

var states = '',  stateOrigin;
var root = document.getElementById("svgCanvas");
var viewport = root.getElementById("viewport");
var storeCo =[];
function setAttributes(element, attribute)
{
    for(var n in attribute) //rool through all attributes that have been created.
    {
     element.setAttributeNS(null, n, attribute[n]);   
    }
}
function setupEventHandlers() //self explanatory;
{
  setAttributes(root, {
      "onmousedown": "mouseDown(evt)", //do function
      "onmouseup": "mouseUp(evt)",
      "onmousemove":  "mouseMove(evt)", 
  }); 
}
setupEventHandlers();

function setTranslate(element, x,y,scale) {
    var m = "translate(" + x + "," + y+")"+  "scale"+"("+scale+")";
      element.setAttribute("transform", m);
}

function getMousePoint(evt) { //this creates an SVG point object with the co-ords of where the mouse has been clicked.
    var points = root.createSVGPoint();
    points.x = evt.clientX;
    points.Y = evt.clientY;
    return points;
}

function mouseDown(evt)
{
    var value;
    if(evt.target == root || viewport)
    {
     states = "pan";   
     stateOrigin = getMousePoint(evt);
        console.log(value);
    }   
}
function mouseMove(evt)
{
    var pointsLive = getMousePoint(evt);
    if(states == "pan")
    {
     setTranslate(viewport,pointsLive.x - stateOrigin.x, pointsLive.Y - stateOrigin.Y, 1.0); //is this re-intializing every turn?
     storeCo[0] = pointsLive.x - stateOrigin.x
     storeCo[1] = pointsLive.Y - stateOrigin.Y;
    }
    else if(states == "store")
    {
        setTranslate(viewport,storeCo[0],storeCo[1],1); // store the co-ords!!!
        stateOrigin = pointsLive; //replaces the old stateOrigin with the new state
        states = "stop";
    }
}
function mouseUp(evt)
{
    if(states == "pan")
    {
     states = "store"; 
        if(states == "stop")
        {
         states ='';   
        }
    }
}

在您的mousedown函数中,您没有考虑到元素可能已经有了转换,而只是覆盖了它。

您将需要查找和解析任何现有的转换。或者,一种更简单的方法是记录旧的x和y偏移量,当发生新的鼠标按下时,将它们添加到新的偏移量中。