3

I have two div containers. the first contains many small SVG Images, the second is supposed to contain an SVG Image you click on.

'On Click' of any of the SVG Images in the first div, I'd like to:

  1. Clone the SVG Image.
  2. Re-scale it (the clone) to 5x its original size.
  3. View it in the 2nd div container.

I've done some research and found i can control the scaling and sizing of an SVG Image using viewBox. So i set the viewBox attribute. A small svg looks like this:

            var small svg = div.append("svg:svg")               
                .attr("class", "thumbnail")
                .attr("width", w)
                .attr("height", h)  
                .attr("viewBox", "0 0 " + w + " " + h)
                .attr("preserveAspectRatio", "none")

                .on("click", function(){
                            var projectedGraph = this.cloneNode(true);


            IncreaseSize(projectedGraph);

            });

Now, in the 'IncreaseSize' method I've done the following:

            projectedGraph.setAttribute("class", "main")
            projectedGraph.setAttribute("width", w*5)
            projectedGraph.setAttribute("height", h*5)
            projectedGraph.setAttribute("viewBox", "0 0 " + (w*5) + " " + (h*5))


            $mainContent.append(projectedGraph); // append to second Div

But the size remains the same (visually). When i 'inspect element' in'Chrome'. The parameters are set. I've spent quite alot of time tweaking the values and trying to understand the problem and each time I increase the 'projectedGraph's viewBox width and height, without reseting the svg's width and height, the image goes smaller

I saw many related questions such as:

and many more but i still cant resolve the issue. What am i doing wrong please?

Community
  • 1
  • 1
Riyanat
  • 141
  • 1
  • 2
  • 8

2 Answers2

1

The width and height attributes control how big an area the SVG drawing occupies. The viewBox controls what content you see. If you increase them both then you'll see more stuff that would otherwise be invisible (outside the drawing area) but each shape will be the same size.

If you want the shapes to get bigger i.e. a zoom like effect then don't change the viewBox.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
0

You know that you don't have to clone the svg if you just want to view it at a different scale, right?

Here's an example.

What it does is it has a nested <svg> element that has a <use> element inside that links to the svg that should be viewed in another scale.

<svg id="mainsvg">
  <g id="map">
    ...
      your unscaled svg here
    ...
  </g>

  <svg id="miniview" viewBox="340 502 100 100" 
   width="200" height="200" x="400" y="60" overflow="hidden">
    <use xlink:href="#map" width="100%" height="100%"/>
  </svg>
</svg>
Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139