需求
把一张雪碧图渲染到页面上,让当前展示的图片看起来像动图一样。使用canvas能简单且快速的做到。
实现步骤
html代码如下:
<canvas id="logo" width="260" height="260.5"></canvas>
js代码如下:
var canvas = document.getElementById("logo");
var ctx = canvas.getContext("2d");
var image = new Image();
let flag = 37;
image.src = "https://42lab.cdn.sunborngame.com/website/anniversary/image/loading-halfbe61f4068b.png";
image.onload = function () {
let index = 0;
cutTimer = setInterval(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 520 * index, 0, 520, 521, 0, 0, 260, 260.5);
index++;
if (index == flag) {
clearInterval(cutTimer);
}
}, 40);
};
总结
drawImage()的参数说明:https://blog.csdn.net/kidoo1012/article/details/75174884/