好吧,我有这个 SVG Canvas 元素,到目前为止,一旦用户单击并拖动 Canvas , Canvas 就会移动,屏幕外的元素就会出现在屏幕上等等......
但是我有这个问题,当用户再次点击并拖动时,平移坐标会重置为 0,这会使 Canvas 跳回到 0,0。
这是我为那些不想使用 JS fiddle 的人准备的代码
这是 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 ='';
}
}
}
最佳答案
在你的 mousedown 函数中,你没有考虑元素可能已经有一个转换的事实,你只是覆盖它。
您将需要查找和解析任何现有的转换。或者更简单的方法是记录旧的 x 和 y 偏移量,并在发生新的 mousedown 时将它们添加到新的偏移量。
关于javascript - SVG Camera Pan - Translate 每次都重置为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28901517/