Draw text in SVG but remove background

前端 未结 2 1108
有刺的猬
有刺的猬 2020-12-10 17:01

I\'m working with an SVG element that should look something like this: (sorry that I have to post this as a link instead of as a picture, but as a new user I didn\'t have pe

相关标签:
2条回答
  • 2020-12-10 17:28

    "Removing the background" of svg text without scripting can be done using svg filters.

    For example:

    <filter x="0" y="0" width="1" height="1" id="removebackground">
       <feFlood flood-color="blue"/>
       <feComposite in="SourceGraphic"/>
    </filter>
    

    Which can be used by the text like this:

    <use xlink:href="#text1" fill="black" filter="url(#removebackground)"/>
    

    This will adapt to the string width automatically. If you need some padding you can tweak the x,y,width,height attributes on the filter element.

    Hmm, thinking of this again, this might not be what you wanted exactly. But it's possible to adapt the above. Here's your file with this solution:

    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%" viewBox="0 0 620 1100" preserveAspectRatio="xMidYMid meet">
        <defs>
            <!--Define some texts-->
            <text id="text1" x="90" y="100" style="text-anchor:start;font-size:30px;">THIS IS MY HEADER</text>
            <text id="text2" x="525" y="1010" style="text-anchor:end;font-size:30px;">MY TEXT HERE</text>
            <filter x="0" y="0" width="1" height="1" id="removebackground">
                <feFlood flood-color="black"/>
            </filter>
    
            <mask id="Mask1">
                <!--draw the entire screen-->
                <rect x="0" y="0" width="620" height="1100" style="fill:white;" />
                <!--Mask out the two rectangles where text is to be placed-->
                <use xlink:href="#text1" filter="url(#removebackground)"/>
                <use xlink:href="#text2" filter="url(#removebackground)"/>
            </mask>
        </defs>
    
        <!--The original background (here a rect with a fill color, but could also be an image)-->      
        <rect x="0" y="0" width="620" height="1100" style="fill:#f0ffb6"/>
        <!--Draw the rectangle but applying the mask-->
        <rect x="100" y="100" rx="20" ry="20" width="420" height="900" mask="url(#Mask1)" style="fill:none;stroke:green;stroke-width:5"/>
    
        <!--Draw the text-->                
        <use xlink:href="#text1" fill="black" stroke="black" stroke-width="1" />
        <use xlink:href="#text2" fill="black" stroke="black" stroke-width="1" />
    
        <text x="200" y="200">This text goes into the border</text>
    </svg>
    
    0 讨论(0)
  • 2020-12-10 17:40

    I believe a simple way to affect this is to use the user's text as a luminance mask with a big stroke-width set & a black stroke. Next, place the text normally over the masked border.

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