How to animate svg mask from js?

How to animate a js mask and mask a layer and svg layer mask? Without using third-party libraries?

<svg id="mask-layer" width="200" height="50"  >
    <defs>
        <mask id="mask">
            <rect width="200" height="50" style="fill: red" />
        </mask>
    </defs>
    <rect id="masked" width="200" height="50" style="fill: red"/>
</svg>  

You need to create a moving mask.

enter image description here

He is looking for an answer all day and despaired. I will be glad to any advice on this topic.

0
source share
2 answers

Using svg mask, you can do something like this:

(function() {
  var btnMove = document.getElementById("btnMove");
  var rect = document.getElementById("rect");
  var pos = 100;
  btnMove.addEventListener("click", function() {
    rect.setAttribute("x", pos);
    pos += 100;
  });
})();
<svg id="mask-layer" width="200" height="50">
  <defs>
    <mask id="mask" style="stroke: #9595C6;">
      <rect width="200" height="50" />
    </mask>
  </defs>
  <rect id="rect" x="0" y="0" width="200" height="50" style="fill: #9595C6;" />
  <rect x="0" y="0" width="200" height="50" mask="url(#mask)" />
</svg>
<br />
<button id="btnMove">Move</button>
Run codeHide result
+1
source

You can draw one rectangle over another.

HTML:

<svg id="mask-layer" width="200" height="50"  >
    <rect id="masked" width="200" height="50" style="fill: blue"/>
    <rect id='mask' width="0" height="50" style="fill: red" />
</svg>

<br />
<span id='progress'></span>

JavaScript:

(function() {
    var mask = document.getElementById('mask');
    var progressSpan = document.getElementById('progress');
    var fullWidth = 200;
    var curWidth = mask.getAttribute('width');

    var calculateProgress = function() {
        var progress = (curWidth*100)/fullWidth;
        progressSpan.innerHTML = ['Progress: ', Math.floor(progress), '%'].join('');
    }

    var interval = setInterval(function() {
        mask.setAttribute('width', ++curWidth);
        calculateProgress();
        if(curWidth > fullWidth) {
            clearInterval(interval);
            progressSpan.innerHTML = 'Finished!';
        }
    }, 50);
})();

Here you have a working example: https://jsfiddle.net/L1vy2t3o/

+1
source

Source: https://habr.com/ru/post/1676444/


All Articles