pc端以及移动端因为有酷炫的动画吸引大众,而其中一种实现方式为canvas帧动画,这里简单的写一个方法仅供参考
var obj = {}
var curImgList = []
var loadIndex = 0
// img加载初始化
const animatInit = (_obj) => {
obj = _obj
obj.imgList.forEach((item) => {
let img = new Image()
img.src = item
img.onload = function () {
curImgList.push(img)
loadIndex++
if (loadIndex === obj.imgList.length - 1) {
animate()
}
}
})
}
// canvas动画
const canvas = $(obj.$ele)[0]
console.log(canvas)
canvas.width = obj.width;
canvas.height = obj.height;
const ctx = canvas.getContext('2d');
var startTime = 0;
var currImg = 0;
function animate() {
window.requestAnimationFrame(function (curTime) {
console.log(curTime)
if (curTime - startTime > 120) {
startTime = curTime
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(curImgList[currImg], 0, 0)
if (currImg >= curImgList.length - 1) {
currImg = 0
} else {
currImg++
}
}
animate()
})
}
export default animatInit
调用方法
import animatie from './animatie'
function importAll(r) {
return r.keys().map(r)
}
var obj = {
width: 750,
height: 1050,
$ele: $('.animation'),
imgList: importAll(require.context('@/img/animation/sprite', false, /\.(png|jpe?g|svg)$/)) // webpack提供的加载方法
}
animatInit(obj)