javascript - 如何检索元素相对于 svg viewbox 的坐标?

标签 javascript google-chrome svg d3.js viewbox

在我的 index.html 中,我有一个 svg viewbox:

<svg viewBox = "0 0 2000 2000" version = "1.1">
</svg>

我希望为我创建的 svg 椭圆制作动画,这样当单击该椭圆时,它会垂直移动到某个我们称为 TOP 的 y 点,如果再次单击,它会回到其原始位置,称为 BOTTOM。目前,我正在使用以下在一定程度上有效的代码。

var testFlag = 0;    
d3.select("#ellipseTest").on("click", function(){
if (testFlag == 0){
  d3.select(this)
      .attr("transform", "translate(0,0)")
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("transform", "translate(0,-650)")
    testFlag = 1;
}else{
 d3.select(this)
      .attr("transform", "translate(0,-650)")
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("transform", "translate(0,0)")
testFlag = 0;
}
});

但是,问题是我还使椭圆可拖动到顶部点和底部点。因此,如果我将椭圆拖到 TOP 和 BOTTOM 之间的中间位置,然后单击椭圆,它会垂直 TOP 上方设置动画,而不是在到达 TOP 时停止(对于 BOTTOM 向下设置动画时也是如此)。这似乎是 transform translate 方法工作方式的结果。 我相信我可以解决这个问题,如果我创建一个函数来动态返回椭圆应该相对于鼠标点击的位置(或者更好的是,到椭圆当前位置)的平移量。问题是我不知道如何获取元素相对于 View 框的当前 y 位置,而只能获取相对于整个页面的位置。

这是我用来获取点击位置的错误代码:

var svg2 = document.getElementsByTagName('svg')[0];
var pt = svg2.createSVGPoint();
document.documentElement.addEventListener('click',function(evt){    
    pt.x = evt.clientX;
    pt.y = evt.clientY;
    console.log('Position is.... ' + pt.y);
},false);

这是我使椭圆可拖动的工作代码:

//These points are all relative to the viewbox
var lx1 = -500;
var ly1 = 1450;
var lx2 = -500;
var ly2 = 800;
function restrict(mouse){ //Y position of the mouse 
    var x;
    if ( (mouse < ly1) && (mouse > ly2) ) {
        x = mouse;
    }else if (mouse > ly1){
        x = ly1;
    }else if (mouse < ly2) {
        x = ly2;
    }
    return x;
}


var drag = d3.behavior.drag()
    .on("drag", function(d) {
      var mx = d3.mouse(this)[0];
      var my = d3.mouse(this)[1];


      d3.select("#ellipseTest")
        .attr({
          cx: lx2,
          cy: restrict(d3.mouse(this)[1])
        });
    })

最佳答案

动画 cy 而不是转换...

var testFlag = 0;    
d3.select("#ellipseTest").on("click", function(){
if (testFlag == 0){
  d3.select(this)
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("cy", 0)
    testFlag = 1;
}else{
 d3.select(this)
      .transition()
        .duration(450)
        .ease("in-out")
        .attr("cy", 650)
testFlag = 0;
}
});

关于javascript - 如何检索元素相对于 svg viewbox 的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12698349/

相关文章:

html - 使用图案制作响应式 Angular svg 形状

javascript - 如何使用dygraphs打印非时间序列

javascript - jQuery UI 设置绝对对话框位置不执行任何操作

google-chrome - Chrome 中的 Azure 无限重定向循环

html - Favicon 未显示在新标签页 Chrome 扩展程序上

performance - SVG 图像和 CPU 使用率

javascript - 如何使用 JQuery 只显示一个 div 的子元素?

javascript - 使用 for 循环推送到数组

android - chrome android设置宽度为100%

javascript - 如何正确使用SVG checkintersection()函数?