1

I have a React application in which I render multiple polygons on SVG element that is the same size as his parent div which has a background-image property. On desktop it looks like this:

enter image description here

So those green buildings are just polygons mounted on svg. On desktop version everything works fine but when I switch to mobile those polygon coordinates are not in the same place because they are saved as desktop version of width and height. This is html part:

    <div className={classes.complexDisplayDiv} style={{ backgroundImage: `url(${photo})` }}>
    <svg
        height={643}
        width={1133}
        className={classes.svg}
    >
        {
            buildings.map((building, index) => {
                return (
                    <polygon
                        points={getPolygonString(building.polygon)}
                        style={{ fill: 'rgba(129,215,66,0.3)', strokeWidth: '1', }}
                    />
                )
            })
        }
      </svg>
   </div>

And this is css part ( I am using Material UI):

complexDisplayDiv: {
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
    backgroundPosition: 'center center',
    height: '643px',
    width: '1133px',
    overflow: 'hidden'
}

complexDisplayDiv refers to div element

I've tried setting div on mobile to be width: "100%" but all I get is this:

enter image description here

mne_web_dev
  • 261
  • 4
  • 12

1 Answers1

0

Quite likely you need a <viewBox> property to make your svg overlay responsive.

So instead of fixed width/height attributes add a viewBox like so:

<svg viewBox="0 0 1333 643">

This way, your polygon will keep proportions or will scale relative to the parent div.

Responsive/resizable example

* {
  box-sizing: border-box;
}

.resize {
  overflow: auto;
  resize: both;
  width: 100%;
  border: 1px dotted #ccc;
  padding: 1em;
}

.mapSvg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  bottom: 0;
}

.complexDisplayDiv {
  position: relative;
  background-image: url(https://i.stack.imgur.com/PohZd.jpg);
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: center center;
  width: 1333px;
  height: 643px;
  max-width: 100%;
  overflow: hidden;
}

@media (max-width:640px) {
  .complexDisplayDiv {
    height: 50vh;
    width: 100%;
  }
}
<div class="resize">
  <div class="complexDisplayDiv">
    <svg class="mapSvg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1333 643">
            <g  fill="green" fill-opacity="0.5">
              <polygon transform="scale(1.9), translate(-10, -285)" points="151.8,405.4 142.9,290.7 217.4,271.3 267.6,353.8 272,459.6 197.4,482.5   " />
            </g>
          </svg>
  </div>
</div>
<p>Resize me!</p>
herrstrietzel
  • 11,541
  • 2
  • 12
  • 34