Scaling SVG Graphics with Javascript
example:
rendered as png for reference:
description
here more about SVG: this doc was my only source for this demonstration. especially the part about scripting is very interesting. this example shows how to rescale a svg more or less dynamically. there are also methods for scaling (rotation, transformation) svg dynamically and as an animation. this doc does the following:
- SVG doc is loaded embedded in the HTML, where an init function in the SVG file's ECMA-script-part ...
- ... registers functions in the top.* space. therefore, a script in this HTML file can call those HTML2svg functions which execute something in the SVG graphic. therefore you have to open the SVG file in a texteditor
- the init function of the HTML file resizes the svg to its initial dimension
relevant code
SVG, in and right after the header ...
onload="RunScript(evt)"
...
...
<script type="text/ecmascript">
<![CDATA[
var g_element;
var SVGDoc;
var SVGRoot;
function RunScript(LoadEvent) {
top.SVGsetDimension = setDimension;
top.SVGsetScale = setScale;
SVGDoc = LoadEvent.target.ownerDocument;
g_element = SVGDoc.getElementById("layer1");
}
function setDimension(w,h) {
SVGDoc.documentElement.setAttribute("width", w);
SVGDoc.documentElement.setAttribute("height", h);
}
function setScale(sw, sh) {
g_element.setAttribute("transform", "scale(" + sw + " " + sh +")");
}
]]>
</script>
HTML
<script type="text/javascript">
var W3CDOM = (document.createElement && document.getElementsByTagName);
window.onload = init;
function init(evt) {
SVGscale(0.5);
}
function SVGscale(scale) {
window.SVGsetDimension(640*scale,480*scale);
window.SVGsetScale(scale,scale);
if (!W3CDOM) return;
var box = document.getElementById('svgid');
box.width = 640*scale;
box.height = 480*scale;
}
</script>
tested to work with following setups
related stuff
Links
license and disclamer note
you can use all or parts of this and only this single site plus the embedded svg file without permission. my aim is to help the adoption of svg as a styling element in HTML sites. this is tested to work flawlessly with
mozilla firefox 1.5. I'm not responsible for any other damage.
feedback