How can I keep text or objects to a fixed size while the background and position coordinates change? For example:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
width="100%" height="100%"
viewBox="0 0 50000 50000"
>
<circle cx="25000" cy="25000" r="100px" fill="red" />
</svg>
In this code, the circle will NOT be 100 pixels, it will be scaled according to the viewbox size, so it will be tiny.
This problem manifests in maps, for example. When you zoom in and out on maps you want the dot representing a city location and the label to stay the same size, not get bigger or smaller when the user zooms.
Apply the inverse of the viewBox scale to the radius e.g.
var circle = document.getElementById('c');
var root = document.getElementById('root');
var matrix = circle.getCTM();
circle.r.baseVal.value /= matrix.a;
<svg id="root" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
width="100%" height="100%"
viewBox="0 0 50000 50000"
>
<circle id="c" cx="25000" cy="25000" r="100px" fill="red" />
</svg>
And if I double the viewBox values the circle stays the same size.
var circle = document.getElementById('c');
var root = document.getElementById('root');
var matrix = circle.getCTM();
circle.r.baseVal.value /= matrix.a;
<svg id="root" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
width="100%" height="100%"
viewBox="0 0 100000 100000"
>
<circle id="c" cx="25000" cy="25000" r="100px" fill="red" />
</svg>
You may want to use an ellipse so you can scale the x and y separately by the matrix a and d values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With