JSFiddle - React, Tailwind, and code Playground
by kzima
HTML
<div id="container">
<svg id="svg" width="100" height="100">
<rect fill="red" width="100" height="100"></rect>
</svg>
</div>
CSS
body {
margin: 8px;
}
#container {
-webkit-transform: translate(50px, 50px);
transform: translateX(50px, 50px);
}
JavaScript
var container = document.querySelector("#container");
var svg = document.querySelector("#svg");
svg.addEventListener("click", (e) => {
// console.log("eventX", e.clientX, "eventY", e.clientY);
var pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
// console.log("point in svg coordinate system", pt);
var actualPoint = pt.matrixTransform(svg.getScreenCTM().inverse())
// console.log("point with applied inverse transformation of getScreenCTM()", actualPoint)
console.log(`Should print (${e.clientX - 50 - 8}, ${e.clientY - 50 - 8}), actual value: (${actualPoint.x}, ${actualPoint.y})`)
})
// to reproduce
// 1. click anywher on the rectangle
// 2. notice result in console log
// 3. The result should be point inside svg (click point minus body padding (8px) minus parent transformation (50px))
// This example works in latest Chrome but it does not work in Firefox 72.0.1 (64-bit)