Search code examples
angularsvgd3.jsscale

Angular - Scaling an inline d3 SVG created in code


This is my first question here, so I apologise if I mess something up.

I'm building a simple SVG in Angular using the d3 library, but I can't get the thing to scale.

I did a whole bunch of reading up on SVG's over here https://css-tricks.com/scale-svg/ and I chose to go with the approach of building the SVG within a viewbox and then applying the width and height attributes.

When inspecting the SVG, I see that it takes up the specified 100px for the width and height, but the SVGElements themselves are still the original size.

BUT! If, instead of setting the width and height through code, I modify the width and height by editing the SVG as HTML in Dev Tools (ie: width="100px" height="100px"), then it scales perfectly!

I've made a plunker here: https://plnkr.co/edit/kYcTocJzi6eA59Yj?preview - The first SVG sets the width and height through code, whereas the second SVG doesn't have them set so that you can try it out in Dev Tools if need be :)

Thanks for your time!


Solution

  • In SVG, viewBox is camelCased, but you typed viewbox:

    const svg2 = d3.select(this.svgContainerRef2.nativeElement)
      .append('svg')
      .attr('viewBox', `0 0 ${circleRadius * 2} ${circleRadius * 2}`);