Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG Capturing Mouse Coordinates

Tags:

javascript

svg

I know questions regarding svg mouse coordinates have been asked here before, but I'm quite puzzled by the current behavior I'm experiencing and none of the threads quite seems to address it.

The method I use for capturing coordinates:

var pt = svg.createSVGPoint();  // Created once for document

function alert_coords(evt) {
    pt.x = evt.clientX;
    pt.y = evt.clientY;

    // The cursor point, translated into svg coordinates
    var cursorpt =  pt.matrixTransform(svg.getScreenCTM().inverse());
    console.log("(" + cursorpt.x + ", " + cursorpt.y + ")");
}

The problem is with converting mouse click coordinates into the svg coordinates in the user space. I'm using the coordinates to drag a rectangle across the screen, and as the cursor gets further to the right in the svg space the coordinates become more and more skewed. To test this in a simple manner, I put three rectangles in global svg space at (100, 500), (500, 500), (1000, 500), and (1000, 200). Using a simple logging function the coordinates I receive(plus or minus 5 for mouse imprecision) are (98, 473), (487, 470), (969, 471), (969, 190). As you can see the further along the x or y axis the mouse goes, the more inaccurate it becomes. I tried to replicate this in a fiddle using the same method for capturing mouse coordinates, but I can't replicate it there... One more thing to note that may be significant is the fact that when I log the svg document, the width and height are set to values slightly less than the viewbox values, ie. 1380 width and 676 height given the viewbox value of "0 0 1400 700". Anyway, here's the fiddle, all the svg properties are the same as they are in my program.

http://jsfiddle.net/ASLma/11/

like image 215
Smerk Avatar asked Oct 05 '12 19:10

Smerk


1 Answers

It seems the problem was opening the svg directly in the browser. Instead, I embedded it in an html page via an embed tag, and it works great. I'm not sure why that would matter in terms of my mouse coordinate accuracy, but a solution is a solution.

like image 165
Smerk Avatar answered Oct 08 '22 12:10

Smerk