2

I have an SVG mask that I would like to rotate the elements inside. However, when I attempted it, it looks like the entire mask is being rotated.

I tried at this SO post, but the fiddle wasn't working (the image wasn't showing anymore). This is what it originally looks like

initial image

What happened

what happened

What I wanted to happen

intended

I wanted only the "liquid" element to be rotated, but somehow the liquid element is being rotated the wrong way.

This is the SVG (with mask element):

<svg width="200px" height="200px" viewBox="0 0 200 200">
    <defs>
        <rect id="path-1" x="75" y="65" width="50" height="100" rx="5"></rect>
    </defs>
    <g id="bottle" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <rect id="bottle-lid" stroke="#916548" stroke-width="5" x="82.5" y="52.5" width="35" height="15" rx="5"></rect>
        <rect id="bottle-holder" stroke="#916548" stroke-width="5" x="117.5" y="55.5" width="30" height="7" rx="3.5"></rect>
        <mask id="mask-2" fill="white">
            <use xlink:href="#path-1"></use>
        </mask>
        <g id="Mask"></g>
        <rect id="bottle-liquid" fill="#3498DB" mask="url(#mask-2)" x="40" y="80" width="120" height="120"></rect>
        <rect id="bottle-outline" stroke="#916548" stroke-width="5" mask="url(#mask-2)" x="77.5" y="67.5" width="45" height="95" rx="5"></rect>
    </g>
</svg>

And this is the JS (I am using a GSAP library)

const liquid = document.querySelector("#bottle-liquid")

const tl = new TimelineMax()

tl.to(liquid, 1, {
  rotation: 20
})

How can I rotate just the a certain element inside a masked SVG?

Iggy
  • 5,129
  • 12
  • 53
  • 87

1 Answers1

3

I've made a few changes to your SVG, the most important: I've putted the bottle-liquid inside a g element and I'm applying the mask to the g element and the transform to the bottle-liquid. I hope it helps.

<svg width="200px" height="200px" viewBox="0 0 200 200">
    <defs>
        <rect id="path-1" x="75" y="65" width="50" height="100" rx="5"></rect>
      
      
        <mask id="mask-2" fill="white">
            <use xlink:href="#bottle-outline"></use>
        </mask>
      
    </defs>
    <g id="bottle" stroke-width="5" stroke="#916548" fill="none" fill-rule="evenodd">
        <rect id="bottle-lid"  x="82.5" y="52.5" width="35" height="15" rx="5"></rect>
        <rect id="bottle-holder"  x="117.5" y="55.5" width="30" height="7" rx="3.5"></rect>
        <g mask="url(#mask-2)">
        <rect id="bottle-liquid" stroke="none" fill="#3498DB"  x="40" y="80" width="120" height="120" transform="rotate(20 100 140)"></rect>
        </g>
        <rect id="bottle-outline" x="77.5" y="67.5" width="45" height="95" rx="5"></rect>
    </g>
</svg>
enxaneta
  • 31,608
  • 5
  • 29
  • 42