Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG polygon with point coordinates in percent [duplicate]

I can use percent values in the coordinates of a rectangle in svg, but not in a polygon. Is there a workaround?

I mean, this is ok:

svg {
  background: #ADF;
  width: 300px;
  height: 300px
}
rect {
  stroke: black;
  fill: #8FF;
}
<svg>
  <rect x="10%" y="10%" width="80%" height="70%"/>
</svg>

But this doesn't work:

svg {
  background: #ADF;
  width: 300px;
  height: 300px
}
polygon {
  stroke: black;
  fill: #8FF;
}
<svg>
  <polygon points="20%,10% 10%,90% 80%,90%"/>
</svg>

Chrome complains

Error: attribute points: Expected number, "20%,10% 10%,90% 80…".

Is there a way I can draw a filled polygon with percent coordinates?

like image 606
Lynn Avatar asked Jan 05 '23 12:01

Lynn


1 Answers

The SVG coordinate system is defined by the viewbox of the SVG.

Define your viewbox as say 0 0 100 100 and translate the percentage points to numbers based on that viewbox.

Then the SVG will scale automatically.

If you want to avoid stroke scaling...there's a CSS property for that too!

svg {
  background: #ADF;
  width: 250px;
  height: 250px
}
polygon {
  stroke: black;
  stroke-width:1;
  fill: #8FF;
  vector-effect: non-scaling-stroke;
}
<svg viewbox=" 0 0 100 100">
  <polygon points="20,10 10,90 80,90" />
</svg>
like image 80
Paulie_D Avatar answered Jan 12 '23 20:01

Paulie_D