Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG scaling in javascript

I am pretty new to SVG and I am stuck on how to scale a shape inside an SVG element.

Can someone explain to me why the following doesn't work? I would like to scale up the circle by 50%.

Here is my jsfiddle with the example which doesn't scale the circle?

https://jsfiddle.net/q2buo2x7/

<svg height="150" width="150" id="outer">
    <circle id="inner" cx="25" cy="20" r="20" fill="orange"/>
</svg>

<script>
    function zoom() {
        var outer = document.getElementById('outer');
        outer.setAttribute("currentScale", 1.5);
    }
    zoom();
</script>
like image 542
user3284707 Avatar asked Jun 22 '15 20:06

user3284707


People also ask

How do I scale an SVG element?

Just set the viewBox on your <svg> , and set one of height or width to auto . The browser will adjust it so that the overall aspect ratio matches the viewBox .

Can SVG integrate with JavaScript?

Details about each SVG attribute. Details about the SVG DOM API, for interaction with JavaScript. SVG works together with HTML, CSS and JavaScript.

How do I resize an SVG file?

❓ How can I resize a SVG image? First, you need to add a SVG image file: drag & drop your SVG image file or click inside the white area to choose a file. Then adjust resize settings, and click the "Resize" button. After the process completes, you can download your result file.

Can SVG be stretched?

An SVG image with fixed dimensions will be treated just like a raster image of the same size. Note: If you are trying to stretch your SVG to a different aspect ratio with CSS—for example in order to stretch it over the page background—make sure your SVG includes preserveAspectRatio="none" .


1 Answers

You can not scale the top-level svg object. To do so, you will need to change the viewBox.

Where did you get the idea to use currentScale as an attribute?

To scale the circle you need to change its transform attribute:

<svg height="150" width="150" id="outer">
    <circle id="inner" cx="25" cy="20" r="20" fill="orange"/>
</svg>

<script>
    function zoom() {
        var circle = document.getElementById('inner');
        circle.setAttribute("transform", "scale(1.5)");
    }
    zoom();
</script>

Read more: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform

like image 188
Brennan Avatar answered Sep 22 '22 23:09

Brennan