APNG动图播放与暂停控制实例页面

回到相关文章 »

效果:

播放速率:

//zxx: 感谢 LuLu UI 提供视觉支持。

代码:

CSS代码:
img, 
canvas { 
    width: 190px; height: 191px;
}
img { visibility: hidden; }
HTML代码:
<img id="chip" src="./chip.png">
<p>
    <button type="primary" id="toggle" is="ui-button">播放/暂停</button>
    <button type="primary" id="stops" is="ui-button">停止</button>
</p>
<p>播放速率: <input type="range" id="rate" is="ui-range" min="0.2" value="1" step="0.1" max="2" data-tips="${value}"></p>
JS代码:
<script src="./apng-js/index.js"></script>
<script>
var parseAPNG = window["apng-js"].default;
// 播放器
var player = null;
// 播放速率
var playbackRate = Number(rate.value);
// 获取图片资源
fetch(chip.src).then(function(response) {
    response.arrayBuffer().then(function(buffer) {
          var apng = parseAPNG(buffer);
        // img 替换成 canvas
        var canvas = document.createElement('canvas');
        canvas.width = apng.width;
        canvas.height = apng.height;
        chip.after(canvas);
        chip.remove();
        // 执行播放
        apng.getPlayer(canvas.getContext('2d')).then(function (p) {
            player = p;
            player.playbackRate = playbackRate;
            player.play();
        });
    });
});

// 播放暂停以及速率的事件的处理
rate.addEventListener('change', function () {
    playbackRate = Number(this.value);
    if (player) {
        player.playbackRate = playbackRate;
    }
});
toggle.addEventListener('click', function () {
    if (player) {
        if (player.paused) {
              player.play();
        } else {
              player.pause();
        }
     }
});
stops.addEventListener('click', function () {
    if (player) {
        player.stop();
    }
});
</script>