Search code examples
javascripthtmlsvg

Can I add a mask to an svg-element without using an id?


I want to assign a svg-mask to a svg-image. I can make this work using an id on the mask like this:

<svg id="svg1" width="5cm" height="5cm" viewBox="0 0 200 200"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
     <defs>
       <mask id="mask">
         <circle cx="100" cy="100" r="100" fill="white"></circle>
       </mask>   
     </defs>
     <rect x="0" y="0" width="200" height="200" fill="red" mask="url(#mask)"></rect>
</svg>

However I want to load this svg multiple times, with a different id in the svg-tag. Therefore I will generate duplicates of the '#mask'-id. Using multiple id's is invalid code. So I want to use a class to refer to the appropriate mask. That means I cannot use the mask=url()-technique.

<svg id="svg2" width="5cm" height="5cm" viewBox="0 0 200 200"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
     <defs>
       <mask class="mask">
         <circle cx="100" cy="100" r="100" fill="white"></circle>
       </mask>   
     </defs>
     <rect x="0" y="0" width="200" height="200" fill="red" mask="url(can't use this)"></rect>
</svg>

Is there a way I can apply a mask to the rect element if the mask has a class instead of id? Maybe using javaScript or some other way I didn't think of.

The full story/context: I am actually making an svg image slider-module for Joomla with php. This php generates a module containing javascript, css and an svg. I use the javascript to animate the mask. I do actually have it working with unique id's. I was just wondering if there is a way to assign a mask to an element without referring to id's. I may want to do this because my code is getting a bit more confusing to read, because I have to use some php in my javascript/svg and css for each unique id.


Solution

  • No. You can only reference masks via an id. You cannot reference SVG masks any other way.