0

I have an SVG of baseball diamond, and I'm trying to set its width and height via the attributes of its parent container.

Here's my fiddle: https://jsfiddle.net/a5mz90jy/6/

Here's my Javascript:

const svgBaseballField = document.getElementById('diamond');
  console.log(svgBaseballField);
  const svgContainer = document.getElementsByClassName('svg_container');
  console.log(svgContainer);

  const svgContainerHeight = svgContainer.clientHeight;
  console.log(svgContainerHeight);
  const svgContainerWidth = svgContainer.clientWidth;

  svgBaseballField.setAttribute("width", svgContainerWidth);
  svgBaseballField.setAttribute("height", svgContainerHeight);

  svgBaseballField.setAttribute("viewBox", "0 0 100 100");

I know something is wrong, because svgContainerHeight and svgContainerWidth are undefined. I also know I need to set the viewport to something.

I also checked this before: How can I make an svg scale with its parent container?

InspectorDanno
  • 935
  • 2
  • 12
  • 23

1 Answers1

1

The SVG you are linking to has a fixed width and height (650 x 500), so you are not going to be able to do it the way you are doing now (ie. via <object>.

You have two options:

  1. Copy the SVG locally and modify it. Add a viewBox attribute and change the width and height to "100%".

    <svg ... width="100%" height="100%" viewBox="0 0 650 500" ... >
    
  2. The other solution is to include the SVG as a background image and take advantage of the CSS background sizing properties.

    .svg_container {
      width: 75%;
      height: 100%;
      background: url(https://upload.wikimedia.org/wikipedia/commons/8/89/Baseball_diamond_clean.svg) blue;
      background-repeat: no-repeat;
      background-size: contain;
    }
    

    https://jsfiddle.net/a5mz90jy/12/

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
  • number one works better for me, thanks! And because I am using the object tag, I still have access to all the XML content, right? (if I wanted to change the fill color of a base in JavaScript, etc) ? – InspectorDanno Apr 02 '18 at 01:43
  • I'm having a lot of trouble selecting the elements in the SVG. I'm using D3 to select them, and I can't. do you think you can post an example in the fiddle? Should I be importing the SVG in D3.xml, or is the tag sufficient enough to do it? – InspectorDanno Apr 03 '18 at 20:34
  • You can't access the SVG directly, you have to access it via the `contentDocument` property of the ``. Are you doing that? See: https://stackoverflow.com/questions/11434916/javascript-accessing-inner-dom-of-svg – Paul LeBeau Apr 04 '18 at 02:50