JSFiddle - React, Tailwind, and code Playground
HTML
<svg width="10cm" height="10cm" viewBox="0 0 1000 1000">
<g transform="scale(0.5)">
<line x1="0" y1="500" x2="1000" y2="500"></line>
<g>
</svg>
CSS
svg {
background: yellow;
}
line {
stroke: red;
stroke-width: 20;
}
JavaScript
const UNITS = ["", "", "%", "ems", "exs", "px", "cm", "mm", "in", "pt", "pc"];
var svg = document.querySelector("svg");
var line = document.querySelector("line");
var userToWorldTransform = line.getTransformToElement(svg);
// Compute points in user space (user units)
var startPointUser = svg.createSVGPoint();
startPointUser.x = line.x1.baseVal.value;
startPointUser.y = line.y1.baseVal.value;
var endPointUser = svg.createSVGPoint();
endPointUser.x = line.x2.baseVal.value;
endPointUser.y = line.y2.baseVal.value;
// Compute points in world space (user units)
var startPointWorld = startPointUser.matrixTransform(userToWorldTransform);
var endPointWorld = endPointUser.matrixTransform(userToWorldTransform);
// Compute points in viewport space (physical units)
var startPointViewport = svg.createSVGPoint();
startPointViewport.x = (startPointWorld.x / svg.viewBox.baseVal.width) * svg.width.baseVal.valueInSpecifiedUnits;
startPointViewport.y = (startPointWorld.y / svg.viewBox.baseVal.height) * svg.height.baseVal.valueInSpecifiedUnits;
var endPointViewport = svg.createSVGPoint();
endPointViewport.x = (endPointWorld.x / svg.viewBox.baseVal.width) * svg.width.baseVal.valueInSpecifiedUnits;
endPointViewport.y = (endPointWorld.y / svg.viewBox.baseVal.height) * svg.height.baseVal.valueInSpecifiedUnits;
// Compute lengths
var lineLengthUser = Math.sqrt(
Math.pow(endPointUser.x - startPointUser.x, 2) +
Math.pow(endPointUser.y - startPointUser.y, 2)
);
var lineLengthWorld = Math.sqrt(
Math.pow(endPointWorld.x - startPointWorld.x, 2) +
Math.pow(endPointWorld.y - startPointWorld.y, 2)
);
var lineLengthViewport = Math.sqrt(
Math.pow(endPointViewport.x - startPointViewport.x, 2) +
Math.pow(endPointViewport.y - startPointViewport.y, 2)
);
console.info("Line length in user space: " + lineLengthUser + " user units");
console.info("Line length in world space: " + lineLengthWorld + " user units");
console.info("Line length in viewport space: " + lineLengthViewport +...