Home > Software engineering >  How to fit svg width/height to be the same as path width/height
How to fit svg width/height to be the same as path width/height

Time:04-09

I have this svg that renders an arrow

<div style="position: absolute; z-index: 0;">
  <svg
    width="373"
    height="280"
    overflow="auto"
    style="position: absolute; left: 630.922px; top: -305px; pointer-events: none;"
  >
    <path
      d="M 20 260 C 20 260, 334.74671750091653 33.15551891825835, 334.74671750091653 33.15551891825835"
      stroke="CornflowerBlue"
      stroke-dasharray="0 0"
      stroke-width="5"
      fill="transparent"
      pointer-events="visibleStroke"
    ></path>
    <g
      fill="CornflowerBlue"
      pointer-events="auto"
      transform="translate(319.89194405571646,25.37183689162216) rotate(-35.78107386189255) scale(30)"
      opacity="1"
    >
      <animate
        dur="0.4"
        attributeName="opacity"
        from="0"
        to="1"
        begin="indefinite"
        repeatCount="0"
        fill="freeze"
      ></animate>
      <path d="M 0 0 L 1 0.5 L 0 1 L 0.25 0.5 z"></path>
    </g>
  </svg>
</div>

This results in

Picture 1

As you can clearly see from the photo (it's an inspect element of the svg element though), the diagonal arrow has blue background even after the arrow's head ends. The same thing counts for the width as well, the blue background is wider than the actual arrow width. Is it possible to fit the svg width/height to be the same on as the path's? The paths looks like this: Picture 2

If possible, how can I achieve this?

CodePudding user response:

Draw your arrows outside the SVG by either changing the path data or by adding a viewBox to the SVG element with a x/y/width/height that shifts the arrows outside the SVG's boundaries. And then add overflow: visible to your SVG element.

CodePudding user response:

In this example I have a viewBox 500 in width and 300 in height. I made a line from the left bottom corner to the top right corner. I turned the arrow into a <marker>. To hide the start and the end of the line I added a stroke-dasharray there the first segment in 0, a space of 1, a segment of 98 and a space of 1 (0 1 98 1). The path length is set to 100.

<svg viewBox="0 0 500 300" width="500">
  <defs>
    <marker id="arrow" viewBox="0 0 1 1" refX="1" refY=".5"
      markerWidth="6" markerHeight="6"
      orient="auto-start-reverse">
      <path d="M 0 0 L 1 0.5 L 0 1 L 0.25 0.5 z" fill="CornflowerBlue" />
    </marker>
  </defs>
  <rect width="500" height="300" fill="#eee"/>
  <line x1="0" y1="300" x2="500" y2="0" stroke-dasharray="0 1 98 1"
    pathLength="100" stroke="CornflowerBlue" stroke-width="5" marker-end="url(#arrow)" />
</svg>

  • Related