How to get the coordinates of an element relative to the svg viewport?

In my index.html, I have svg viewbox:

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

I want to animate the svg ellipse that I created in such a way that when I click the ellipse it moves vertically to a specific point y, which we will call TOP, and if you click again, it will return to its original BOTTOM position. I am currently using the following code, which works to some extent.

 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; } }); 

However, the problem is that I also made an ellipse with drag and drop to the TOP point and to the BOTTOM point. Therefore, if I drag the ellipse halfway between TOP and BOTTOM, then click the ellipse, it will animate vertically above TOP, and not stop when it reaches TOP (and, like wise for BOTTOM when animating down). This seems to be the result of how the transformation transformation method works. I believe that I can solve this problem if I create a function that dynamically returns the amount that the ellipse should translate relative to where the mouse click is (or, better yet, where the ellipse is currently located). The problem is that I cannot figure out how to get the current y position of the element relative to the viewport, instead I can only get the position relative to the whole page.

Here is the malfunction code that I use to get the position of my click:

 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); 

Here is my working code to make the ellipse draggable:

 //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]) }); }) 
+4
source share
1 answer

cy animation instead of transform ...

 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; } }); 
+2
source

Source: https://habr.com/ru/post/1437475/


All Articles