Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Adding SVG Mask using js

I'm using a combination of jquery and two.js to create an animated svg. I'm experiencing a weird bug whereby the markup is added incorrectly and not rendered by the browser.

The really strange part is that if I open up the inspector in chrome and select 'edit as html' on the mask element and add any extra element to the mask, the whole thing gets rendered as expected.

I copied/pasted the html and discovered this:

style="mask: url("#mask1");"

I'm using vanilla js to set the style:

document.querySelector('#two_106').style.mask = "url('#mask1')"

but to no avail.

here's the important bits of the markup:

<svg version="1.1" width="1339" height="805" style="overflow: hidden; display: block; top: 0px; left: 0px; right: 0px; bottom: 0px; position: fixed;">

    <defs>
        <mask id="mask1" x="0" y="0" width="1000" height="1000">
            <g id="two_2" transform="matrix(1 0 0 1 0 0)" opacity="1">
                <!-- path elements -->
            </g>
        </mask>
    </defs>

    <g id="two_106" transform="matrix(1 0 0 1 0 0)" opacity="1" style="mask: url(&quot;#mask1&quot;);"> 
<!-- path elements -->
    </g>

</svg>
like image 210
Hello World Avatar asked Jun 01 '26 11:06

Hello World


1 Answers

You actually want this...

document.querySelector('#two_106').style.mask = "url(#mask1)"

The single quotes get turned into html escape characters but you don't need them anyway.

like image 188
Robert Longson Avatar answered Jun 04 '26 01:06

Robert Longson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!