How to animate a mask svg from js?

2019-08-10 06:48发布

问题:

How to animate using js mask, and masked the layer and layer mask svg? 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>  

Need to make a moving mask.

Was looking for an answer all day and is desperate. I will be glad to any advice on the topic.

回答1:

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>



回答2:

You can draw one rect 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 working example: https://jsfiddle.net/L1vy2t3o/