一个canvas实现序列帧的案例-开红包动画:initCanvas(callback){
let canvas = document.querySelector('#canvas'); //获取canvas对象
canvas.width = '300';
canvas.height = '300';
let ctx = canvas.getContext('2d'); //获取2d上下文
let frame = 0 //帧数
let img = new Image(); //创建img
img.src = 'https://p5./d/inn/bec43552e015/line3.png';//给img添加资源
let imgW = 8000;//整张大图的宽度
let x = 0, y = 0, w = 400, h = 400, iX = 0, iY = 0;
let animate = function() {
//定义一个帧数的变量,函数每一帧执行一次,则frame就加一次,以此记录帧数
frame++;
ctx.clearRect(0, 0, canvas.width, canvas.height)
//每过8帧执行一次 x += w 以此达到切换图片的效果
if(frame % 8 === 0 ) {
x += w
if (x >= imgW - w) { //判定当走到最后一张
callback && callback();
return;
}
}
//每隔一帧就执行绘画飞机的操作
ctx.drawImage(img, x, y, w, h, iX, iY, 300, 300);
//为避免frame加到太大,在这里做一个当frame加到10000时,又让它为0的操作
if(frame > 10000 ) {
frame = 0;
}
//利用requestAnimationFrame达到动画效果
requestAnimationFrame(animate);
}
img.onload = function(){
//定义变量:图片截取的位置(x,y) 图片截取的宽高(w,h), 截取的飞机在canvas中的位置(iX, iY)
animate();
}
}
帧图片素材
一张图片上放满每一帧的图片,eg:
欢迎转载,请注明本文的链接地址:
如果觉得《前端实现序列帧_canvas实现序列帧动画的案例》对你有帮助,请点赞、收藏,并留下你的观点哦!