javascript - Translating browser click event `x` and `y` coordinates to coordinates on a scaled Snap svg element -
i needed add piece of text svg rendered snap, @ point user clicks.
because svg scaled using 100% width , uses viewbox
attribute, needed translate x
, y
coordinates provided browser's click event x
, y
coordinates on scaled svg.
i managed make work using piece of code:
var $canvas = $('svg#myscaledsvg'); var snap = new snap($canvas[0]); snap.mousedown(function(event) { var offset = $canvas.offset(); var matrix = snap.transform().diffmatrix.invert(); var x = matrix.x(event.pagex - offset.left, event.pagey - offset.top); var y = matrix.y(event.pagex - offset.left, event.pagey - offset.top) // below function call renders text element given x , y coords addsometext(x, y); });
now, understand why need subtract offsets. don't understand snap.transform().diffmatrix.invert()
does.
can enlighten me why works? can't snap documentation, seems rather sparse overall.
i'm guessing in case, can swap diffmatrix globalmatrix , still work ?
snap stores 3 matrices on response transform() method. localmatrix, diffmatrix , globalmatrix.
localmatrix transform existing on element
globalmatrix matrix viewport element being applied
diffmatrix difference between them.
for globalmatrix may worth looking @ getctm passes through native method. localmatrix @ transforms on element (likely none on svg element doesn't support transforms).
so when looking @ browser, view may zoomed in, panned etc, have viewbox. coordinates of mouse, need converted coordinate space, 1 element in. thats inverse of globalmatrix do, convert mouse. i'm assuming diffmatrix , globalmatrix (getctm) mean same in case (because svg element no transform applied).
if doesn't make sense, may worth doing bit of looking @ svg coordinate space tutorials can quite helpful.
edit: i'm adding bit more info try , below...
jsfiddle i've done, has example using similar code op.
jsfiddle 2 similar responsive, in console log see matrix scale vary
the svg scaled 4, zoomed in following...
height="800" width="800" viewbox="0 0 200 200"
or
height="100%" width="100%" viewbox="0 0 200 200"
there circle @ 25,25, click on circle in fiddle.
the mouse event round 100,100 in user/browser event space (there offset there consider, maybe 108,108 or depending).
so scale of 4, need convert 100,100 account scale, otherwise appear off screen.
if display on svg zoomed 4, need use 1/4 of value display @ correct coordinates possibly useful simplistic way of looking @ it.
how that? invert scale (or whatever transform there). want scale of 0.25 convert 100,100 25,25 appears @ correct places on screen, because zoomed in (as scaled 4 svg parameters).
and yes, localmatrix doesn't make sense on svg element (but not problem either). make sense if group transform on or other element.
its worth noting snap passes parameters x,y mousedown func, use that, rather event.pagex/pagey.
Comments
Post a Comment