Search code examples
svgsnap.svgsvg-animate

Gradually change fill in SVG element using transform in Snap SVG


I am trying to simulate gradually "filling" (like water filling a cup) an element in SVG. I run into trouble with mask. For the following, assume inclusion of snap.svg-min.js:

<script>
var s = Snap(500,500);
var a = s.rect(0,100,100,100);
var b = s.ellipse(50,50,30,60);
b.attr({
    fill: "white"
});
a.animate({transform: 't0, -100'}, 500, mina.easin);
a.attr({
    mask: b
});
</script>

The mask in the a.attr clips the image initially, and shifts that up. I want to fill the ellipse going up.

Somewhat like the inverse of the following:

<script>
var s = Snap(500,500);
var a = s.rect(0,100,100,100);
var b = s.ellipse(50,50,30,60);
b.attr({
    fill: "white"
});
a.animate({transform: 't0, -100', mask: b}, 500, mina.easin);
</script>

Solution

  • You're partly there, there's a few different ways, you could probably also use a clip rather than a mask, but here's the way along the lines I think you were trying...

    Swap the mask around..

    var a = s.rect(0,0,120,120).attr({ fill: 'white', transform: 't0,100' });
    var b = s.ellipse(50,50,30,60);
    
    b.attr({
        fill: "red",
        mask: a
    });
    
    a.animate({transform: 't0,60' }, 2000, mina.easin)
    

    jsfiddle