I spent some time figuring it out, but I finally cracked the math puzzle. This method involves three key steps:
- Include this particular script on your webpage (in conjunction with the SVGPan.js script), for example,
<script xlink:href="SVGPanUnscale.js"></script>
- Identify the elements you do not want to scale (e.g., place them in a group with a distinct class or ID, or assign a specific class to each element) and instruct the script how to locate those items, for instance,
unscaleEach("g.non-scaling > *, circle.non-scaling");
- Utilize
transform="translate(…,…)"
to position each element on the diagram, as opposed to cx="…" cy="…"
.
By following these steps alone, scaling and panning with SVGPan will have no impact on the scale (or rotation, or skew) of designated elements.
Demo:
Library
// Copyright 2012 © Gavin Kistner, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bf9effcfd7cdd0d8c591d1dacb">[email protected]</a>
// License: http://phrogz.net/JS/_ReuseLicense.txt
// Cancel out the scaling for selected elements inside an SVGPan viewport
function unscaleEach(selector){
if (!selector) selector = "g.non-scaling > *";
window.addEventListener('mousewheel', unzoom, false);
window.addEventListener('DOMMouseScroll', unzoom, false);
function unzoom(evt){
// getRoot is a global function exposed by SVGPan
var r = getRoot(evt.target.ownerDocument);
[].forEach.call(r.querySelectorAll(selector), unscale);
}
}
// Counteract all transforms applied above an element.
// Apply a translation to the element so it stays at a local position
function unscale(el){
var svg = el.ownerSVGElement;
var xf = el.scaleIndependentXForm;
if (!xf){
// Keep a single transform matrix in the stack for fighting transformations
// Be sure to apply this transform after existing transforms (translate)
xf = el.scaleIndependentXForm = svg.createSVGTransform();
el.transform.baseVal.appendItem(xf);
}
var m = svg.getTransformToElement(el.parentNode);
m.e = m.f = 0; // Ignore (preserve) any translations done up to this point
xf.setMatrix(m);
}
Demo Code
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Scale-Independent Elements</title>
<style>
polyline { fill:none; stroke:#000; vector-effect:non-scaling-stroke; }
circle, polygon { fill:#ff9; stroke:#f00; opacity:0.5 }
</style>
<g id="viewport" transform="translate(500,300)">
<polyline points="-100,-50 50,75 100,50" />
<g class="non-scaling">
<circle transform="translate(-100,-50)" r="10" />
<polygon transform="translate(100,50)" points="0,-10 10,0 0,10 -10,0" />
</g>
<circle class="non-scaling" transform="translate(50,75)" r="10" />
</g>
<script xlink:href="SVGPan.js"></script>
<script xlink:href="SVGPanUnscale.js"></script>
<script>
unscaleEach("g.non-scaling > *, circle.non-scaling");
</script>
</svg>