Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping SVG elements to a fixed size while position scales

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.

like image 417
Tyler Durden Avatar asked Jan 16 '15 19:01

Tyler Durden


1 Answers

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.

like image 159
Robert Longson Avatar answered Nov 09 '22 18:11

Robert Longson