SVG and JavaScript: transform viewport coordinates into element coordinates

A couple of months ago I built a JavaScript application that allows adding points and labels to locations on a building floorplan. The whole canvas (not HTML <canvas>) is a SVG document inside an HTML document and points/objects/labels/etc. are added to that canvas as native SVG elements. Users can add/move objects on the floorplan but also zoom and pan the floorplan itself. When performing these actions it is important to transform coordinates from the screen or viewport (like the position of your mouse/fingers) into coordinates that make sense in your SVG element’s coordinate system. ...

January 13, 2023