SVG Line with Gradient Stroke Won't Display Straight

前端 未结 3 1350
迷失自我
迷失自我 2020-11-27 20:45

I\'m attempting to replicate an


with SVG. Now, making a straight line with SVG works perfectly, but the second I stroke it with a gradient it will no
相关标签:
3条回答
  • 2020-11-27 21:24

    Assuming you do not want any in-accuracy at all, you can change the line to a filled path as below

    <path d='M 40 209.5 L 460 209.5 L 460 210.5 L 40 210.5' fill='url(#grad1)' />
    

    or alternatively to a filled rect as below

    <rect x=40 y=209.5 width=420 height=1 fill='url(#grad1)' />
    

    It is also interesting to note that this issue only affects vertical and horizontal lines. Slanted line display correctly.

    0 讨论(0)
  • 2020-11-27 21:37

    Robert Longson gives an excellent explanation. But sometimes userSpaceOnUse is a pain, because it spreads the interpolation over the entire canvas, instead of just the line.

    Instead, you could add a tiny amount to the values, to ensure the bbox size is not zero.

    For example,

      <line x1="40" y1="210" x2="460" y2="210.001" stroke="url(#grad1)" stroke-width="1" />
    

    will draw a straight line with gradient.

    0 讨论(0)
  • You are getting caught out by the last paragraph in this part of the SVG specification

    Keyword objectBoundingBox should not be used when the geometry of the applicable element has no width or no height, such as the case of a horizontal or vertical line, even when the line has actual thickness when viewed due to having a non-zero stroke width since stroke width is ignored for bounding box calculations. When the geometry of the applicable element has no width or height and objectBoundingBox is specified, then the given effect (e.g., a gradient or a filter) will be ignored.

    objectBoundingBox is the default for gradientUnits so you need to use gradientUnits="userSpaceOnUse" and then adjust the values to be appropriate for the different coordinate system.

    0 讨论(0)
提交回复
热议问题