antfu / drauu

Headless SVG-based drawboard in browser.
https://drauu.netlify.app/
MIT License
1.2k stars 64 forks source link

Fix getMousePosition when svg has viewBox #4

Closed AlexanderMykulych closed 3 years ago

AlexanderMykulych commented 3 years ago

Hi! Firstly thanks for this awesome library :muscle: I want to use it in my pet project, where I work with SVG a lot, and I found a small bug. When we use viewBox on SVG, then getMousePosition works incorrectly. The proper way that I found is kinda this:

// Find your root SVG element
var svg = document.querySelector('svg');

// Create an SVGPoint for future math
var pt = svg.createSVGPoint();

// Get point in global SVG space
function cursorPoint(evt){
  pt.x = evt.clientX; pt.y = evt.clientY;
  return pt.matrixTransform(svg.getScreenCTM().inverse());
}

svg.addEventListener('mousemove',function(evt){
  var loc = cursorPoint(evt);
  // Use loc.x and loc.y here
},false);

the original answer is here: https://stackoverflow.com/a/10298843/4729613

the reproduction link is here: https://codesandbox.io/s/muddy-feather-7k78f?file=/src/index.js