user3284707
user3284707

Reputation: 3341

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>

Upvotes: 13

Views: 29186

Answers (3)

Brennan
Brennan

Reputation: 5722

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

Upvotes: 11

hvk
hvk

Reputation: 438

    function zoomIn1() {
        var outer = document.getElementById("outer");
        outer.setAttribute("currentScale", 1.5);
    }
    function zoomIn2() {
        var outer = document.getElementById("outer");
        outer.currentScale = 1.5;
    }
    function zoomIn3() { // Correct way
        var inner = document.getElementById("inner");
        inner.setAttribute("transform", "scale(1.5)");
    }

In IE zoomIn1, zoomIn2 and zoomIn3 will work.

In Chrome zoomIn1 will do nothing, zoomIn2 will zoom the whole page and zoomIn3 will do what you want. So for your Microsoft Exam your answer is correct, but in real live: use the transform attribute as stated in zoomIn3.

Upvotes: 13

Paul LeBeau
Paul LeBeau

Reputation: 101800

It depends what you mean by "scale up the circle". You can apply a transform as per Brennan's answer. That will scale up everything about the circle, such as its stroke size, fill, etc.

Or you can just increase the radius of the circle, if that's all you need:

function zoom() {
    var inner = document.getElementById('inner');
    inner.r.baseVal.value *= 1.5;
}
zoom();
<svg height="150" width="150" id="outer">
    <circle id="inner" cx="25" cy="20" r="20" fill="orange"/>
</svg>

Upvotes: 1

Related Questions