SVG scaling in javascript

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

Can someone explain to me why the following does not work? I would like to increase the circle by 50%.

Here is my jsfiddle with an example that does not 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> 
+7
javascript html5 svg
source share
3 answers

You cannot scale top level svg object. To do this, 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> 

More details: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform

+4
source share
  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 will work zoomIn2 and zoomIn3.

In Chrome, zoomIn1 will not do anything, zoomIn2 will enlarge the entire page, and zoomIn3 will do what you want. So, for your Microsoft exam, your answer is correct, but in real life: use the transform attribute as specified in zoomIn3.

+8
source share

It depends on what you mean by circle scaling. You can apply the transform according to Brennan's answer. This will increase everything around the circle, for example, its size, size, 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> 
0
source share

All Articles