SVG摄像机平移 - 翻译每次都保持重置为0?

时间:2015-03-06 15:01:52

标签: javascript jquery css canvas svg

我有这个SVG画布元素,到目前为止,我已经达到了这一点,一旦用户点击并拖动画布移动,屏幕外元素就会出现在屏幕上等......

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

以下是我为那些想要使用JS小提琴的人提供的代码

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

编辑:得到了解决方案 - 这是一个JSfiddle DEMO 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 ='';   
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在你的mousedown函数中,你没有考虑到元素可能已经有一个转换而你只是覆盖它的事实。

您将需要查找并解析任何现有转换。或者更简单的方法是保留旧的x和y偏移的记录,并且当新的mousedown发生时将它们添加到新的偏移量。