ChatGPT解决这个技术问题 Extra ChatGPT

Can you control how an SVG's stroke-width is drawn?

Currently building a browser-based SVG application. Within this app, various shapes can be styled and positioned by the user, including rectangles.

When I apply a stroke-width to an SVG rect element of say 1px, the stroke is applied to the rect’s offset and inset in different ways by different browsers. This is proving to be troublesome, especially when I try to calculate the outer width and visual position of a rectangle and position it next to other elements.

For example:

Firefox adds 1px inset (bottom and left), and 1px offset (top and right)

Chrome adds 1px inset (top and left), and 1px offset (bottom and right)

My only solution so far would be to draw the actual borders myself (probably with the path tool) and position the borders behind the stroked element. But this solution is an unpleasant workaround, and I’d prefer not to go down this road if possible.

So my question is, can you control how an SVG’s stroke-width is drawn on elements?

there are filter hacks you can use to achieve this - but it's not a great solution
There is the paint-order parameter, where you can specify, that the fill should be rendered on top of the stroke, so you will get the "outside alignment", see jsfiddle.net/hne0kyLg/1
Found a way to do this using css 'outline-' attributes: codepen.io/badcat/pen/YVzmYY. Not sure what's the support for this across browsers, but might be useful.
SVG 2 also introduces new paint-order property (SVG 2 implementation seems to be in progress in Chrome).

P
Phrogz

No, you cannot specify whether the stroke is drawn inside or outside an element. I made a proposal to the SVG working group for this functionality in 2003, but it received no support (or discussion).

https://i.stack.imgur.com/I0KEg.png

As I noted in the proposal,

you can achieve the same visual result as "inside" by doubling your stroke width and then using a clipping path to clip the object to itself, and

you can achieve the same visual result as 'outside' by doubling the stroke width and then overlaying a no-stroke copy of the object on top of itself.

Edit: This answer may be wrong in the future. It should be possible to achieve these results using SVG Vector Effects, by combining veStrokePath with veIntersect (for 'inside') or with veExclude (for 'outside). However, Vector Effects are still a working draft module with no implementations that I can yet find.

Edit 2: The SVG 2 draft specification includes a stroke-alignment property (with center|inside|outside possible values). This property may make it into UAs eventually.

Edit 3: Amusingly and dissapointingly, the SVG working group has removed stroke-alignment from SVG 2. You can see some of the concerns described after the prose here.


Thought that might be the case. To solve this I've written a wrapper function for getBBox() called getStrokedBBox(). This wrapper returns the BBox according to how the browser applies strokes to the inset and offset of a shape. It's not perfect (need to keep checking against latest browser versions) but it does accurately provide a shapes outer width for now.
@Phrogz maybe we'll see it before 10 years have passed. svgwg.org/svg2-draft/painting.html#SpecifyingStrokePaint annotation
It's finally here! I, for one, have really been urging for this property to arrive.
I created a svg-contour script for tracing contour of any SVGGeometryElement which can be used as a workaround of stroke-alignment, for anyone interested you can find a description here
Is there any page where I can upvote for the proposal? Thanks. Seems ridiculous it is not supported.
g
gilly3

UPDATE: The stroke-alignment attribute was on April 1st, 2015 moved to a completely new spec called SVG Strokes.

As of the SVG 2.0 Editor’s Draft of February 26th, 2015 (and possibly since February 13th), the stroke-alignment property is present with the values inner, center (default) and outer.

It seems to work the same way as the stroke-location property proposed by @Phrogz and the later stroke-position suggestion. This property has been planned since at least 2011, but apart from an annotation that said

SVG 2 shall include a way to specify stroke position

, it has never been detailed in the spec as it was deferred - until now, it seems.

No browser support this property, or, as far as I know, any of the new SVG 2 features, yet, but hopefully they will soon as the spec matures. This has been a property I personally have been urging to have, and I'm really happy that it's finally there in the spec.

There seems to be some issues as to how to the property should behave on open paths as well as loops. These issues will, most probably, prolong implementations across browsers. However, I will update this answer with new information as browsers begin to support this property.


stroke-alignment is specified in SVG Strokes, a W3C Working Draft. Meanwhile, the SVG 2 W3C Editor’s Draft says that a stroke positioning property shall be in the SVG spec at svgwg.org/svg2-draft/painting.html#SpecifyingStrokePaint, but that spec has already reached W3C Candidate Recommendation status and no such property is in the spec aside from a link to the stroke-position proposal, making it seem like that won't be the case.
B
Bharata

I found an easy way, which has a few restrictions, but worked for me:

define the shape in defs

define a clip path referencing the shape

use it and double the stroke with as the outside is clipped

Here a working example:


The best answer I found
Clever solution. Thanks
This should be accepted as answer. Using and is the most elegant solution currently available.
Nice solution. How would you reverse it to make an outside stroke?
Why the top-level <use>? Why not just put the path and clip path in directly? This works just fine: <svg width="240" height="240" viewBox="0 0 1024 1024"> <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z" clip-path="url(#clip)" stroke="#0081C6" stroke-width="160" fill="#00d2b8"/> <clipPath id="clip"> <use xlink:href="#ld"/> </clipPath> </svg>. (Yes, this is completely reasonable and correct SVG and will render correctly everywhere. Fear no recursion.)
X
Xavier Ho

You can use CSS to style the order of stroke and fills. That is, stroke first and then fill second, and get the desired effect.

MDN on paint-order: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/paint-order

CSS code:

paint-order: stroke;

This is perfect! Thanks for sharing
The linked documentation doesn't seem to indicate whether the stroke is inside, outside, or centered? Could you clarify how to control where the stroke is drawn? Thanks.
The stroke is centred, just as it always was—but if you have a solid fill, the effect of adjusting the paint order to paint stroke first is that the inner half of the stroke is painted over, which has the same effect as drawing a half-as-thick stroke outside.
It's a good workaround as long as the fill is solid. If it's transparent, then the inner half of the stroke becomes visible, just like with the standard order.
How can I make it stroke inside? It made a stroke outside.
S
Steve

Here's a function that will calculate how many pixels you need to add - using the given stroke - to the top, right, bottom and left, all based on the browser:

var getStrokeOffsets = function(stroke){

        var strokeFloor =       Math.floor(stroke / 2),                                                                 // max offset
            strokeCeil =        Math.ceil(stroke / 2);                                                                  // min offset

        if($.browser.mozilla){                                                                                          // Mozilla offsets

            return {
                bottom:     strokeFloor,
                left:       strokeFloor,
                top:        strokeCeil,
                right:      strokeCeil
            };

        }else if($.browser.webkit){                                                                                     // WebKit offsets

            return {
                bottom:     strokeCeil,
                left:       strokeFloor,
                top:        strokeFloor,
                right:      strokeCeil
            };

        }else{                                                                                                          // default offsets

            return {
                bottom:     strokeCeil,
                left:       strokeCeil,
                top:        strokeCeil,
                right:      strokeCeil
            };

        }

    };

u
user1574945

As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.

The specification for strokes in Adobe's PostScript Manual 2nd edition states: "4.5.1 Stroking: The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)

The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.

Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.


F
F Lekschas

Here is a work around for inner bordered rect using symbol and use.

Example: https://jsbin.com/yopemiwame/edit?html,output

SVG:

<svg>
  <symbol id="inner-border-rect">
    <rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
  </symbol>
  ...
  <use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>

Note: Make sure to replace the ? in use with real values.

Background: The reason why this works is because symbol establishes a new viewport by replacing symbol with svg and creating an element in the shadow DOM. This svg of the shadow DOM is then linked into your current SVG element. Note that svgs can be nested and every svg creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.


T
The Witness

I don’t know how helpful will that be but in my case I just created another circle with border only and placed it “inside” the other shape.


m
max-lt

A (dirty) possible solution is by using patterns,

here is an example with an inside stroked triangle :

https://jsfiddle.net/qr3p7php/5/

<style>
#triangle1{
  fill: #0F0;
  fill-opacity: 0.3;
  stroke: #000;
  stroke-opacity: 0.5;
  stroke-width: 20;
}
#triangle2{
  stroke: #f00;
  stroke-opacity: 1;
  stroke-width: 1;
}    
</style>

<svg height="210" width="400" >
    <pattern id="fagl" patternUnits="objectBoundingBox" width="2" height="1" x="-50%">
        <path id="triangle1" d="M150 0 L75 200 L225 200 Z">
    </pattern>    
    <path id="triangle2" d="M150 0 L75 200 L225 200 Z" fill="url(#fagl)"/>
</svg>

h
hirunatan

The solution from Xavier Ho of doubling the width of the stroke and changing the paint-order is brilliant, although only works if the fill is a solid color, with no transparency.

I have developed other approach, more complicated but works for any fill. It also works in ellipses or paths (with the later there are some corner cases with strange behaviour, for example open paths that crosses theirselves, but not much).

The trick is to display the shape in two layers. One without stroke (only fill), and another one only with stroke at double width (transparent fill) and passed through a mask that shows the whole shape, but hides the original shape without stroke.

  <svg width="240" height="240" viewBox="0 0 1024 1024">
  <defs>
    <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
    <mask id="mask">
      <use xlink:href="#ld" stroke="#FFFFFF" stroke-width="160" fill="#FFFFFF"/>
      <use xlink:href="#ld" fill="#000000"/>
    </mask>
  </defs>
  <g>
    <use xlink:href="#ld" fill="#00D2B8"/>
    <use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="red" mask="url(#mask)"/>
  </g>
  </svg>

Y
Yoki Yu

The easiest way I found is to add clip-path into circle

Add clip-path="circle()"

<circle id="circle" clip-path="circle()" cx="100" cy="100" r="100" fill="none" stroke="currentColor" stroke-width="5" />

Then the stroke-width="5" will magically become inner 5px stroke with absolute 100px radius.


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now