Home > Software design >  Draw a circle in svg with preserveAspectRatio="none"
Draw a circle in svg with preserveAspectRatio="none"

Time:12-28

I have an svg with viewBox="0 0 100 100" preserveAspectRatio="none" since I need to draw some elements with reference to percentages.

If I now draw a <circle cx="30" cy="50" r="0.5" stroke="white"/> though it becomes stretched/distorted as well.

Is there a way to tell the circle element to preserve its own aspect ratio?

CodePudding user response:

If all you need is a circle you can use a very short, very wide line like in the following example.

This will work because

  • stroke-linecap="round" will give the illusion of a circle and because
  • strokes can take a vector-effect="non-scaling-stroke".

non-scaling-stroke This value modifies the way an object is stroked. Normally stroking involves calculating stroke outline of the shape's path in current user coordinate system and filling that outline with the stroke paint (color or gradient). The resulting visual effect of this value is that the stroke width is not dependent on the transformations of the element (including non-uniform scaling and shear transformations) and zoom level.

div {
  width: 300px;
  height: 50px;
  background-color: lime;
}

svg {
  width:100%;
  height:100%;
}
<div>
  <svg viewBox="0 0 100 100" preserveAspectRatio="none">
    <!--<circle cx="30" cy="50" r="20"></circle>-->
    <line  x1="30" y1="50" x2="30.1" y2="50" stroke-width="40" stroke="black" stroke-linecap="round" vector-effect="non-scaling-stroke" />
  </svg>
</div>

If you need a white stroke too you can add a white line behind the black one with a bigger stroke width

div {
  width: 300px;
  height: 50px;
  background-color: lime;
}

svg {
  width:100%;
  height:100%;
}
<div>
  <svg viewBox="0 0 100 100" preserveAspectRatio="none">
    
    <line  x1="30" y1="50" x2="30.1" y2="50" stroke-width="45" stroke="white" stroke-linecap="round" vector-effect="non-scaling-stroke" />
    <line  x1="30" y1="50" x2="30.1" y2="50" stroke-width="40" stroke="black" stroke-linecap="round" vector-effect="non-scaling-stroke" />

  </svg>
</div>

  • Related