Search code examples
htmlsvgsvg-animatesvg-filters

HTML SVG texts with different background colors


I have an image and I want to render multiple labels with different background colors:

    <!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 1024">
            <image width="1024" height="1024" xlink:href="https://www.serebii.net/pokearth/paldea.jpg"></image>

            <a xlink:href="#test1">
                <filter x="0" y="0" width="1" height="1" id="solid">
                    <feFlood flood-color="red" result="bg1" />
                    <feMerge>
                        <feMergeNode in="bg1" />
                        <feMergeNode in="SourceGraphic" />
                    </feMerge>
                </filter>

                <text filter="url(#solid)" x="110" y="180" font-size="50">Test 1</text>
            </a>

            <a xlink:href="#test2">
                <filter x="0" y="0" width="1" height="1" id="solid">
                    <feFlood flood-color="yellow" result="bg2" />
                    <feMerge>
                        <feMergeNode in="bg2" />
                        <feMergeNode in="SourceGraphic" />
                    </feMerge>
                </filter>

                <text filter="url(#solid)" x="20" y="50" font-size="50">Test 2</text>
            </a>
        </svg>
    </body>
</html>

However, the text labels always set the first filter color defined in the first (red). How can I separate so every label have it's own color? I've tried giving differente mergeNodes id but it doesn't work.


Solution

  • You now have the same id in the filters, but it must be unique:

    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 1024">
        <image width="1024" height="1024" xlink:href="https://www.serebii.net/pokearth/paldea.jpg"></image>
    
        <a xlink:href="#test1">
             <filter x="0" y="0" width="1" height="1" id="solid1">
                  <feFlood flood-color="red" result="bg1" />
                  <feMerge>
                        <feMergeNode in="bg1" />
                        <feMergeNode in="SourceGraphic" />
                  </feMerge>
             </filter>
    
             <text filter="url(#solid1)" x="110" y="180" font-size="50">Test 1</text>
        </a>
    
        <a xlink:href="#test2">
             <filter x="0" y="0" width="1" height="1" id="solid2">
                  <feFlood flood-color="yellow" result="bg2" />
                  <feMerge>
                        <feMergeNode in="bg2" />
                        <feMergeNode in="SourceGraphic" />
                  </feMerge>
             </filter>
    
             <text filter="url(#solid2)" x="20" y="50" font-size="50">Test 2</text>
        </a>
    </svg>