<style lang="less">
@import './rebbit.less';
</style>
<template>
<div class="rabiit_ll" v-if="isShowRabbit">
<canvas ref="rabbitId" :style="`width:${scale * 108}px;height:${scale * 120}px;`"/>
<div class="hand_view" :style="`width:${scale * 108}px;height:${scale * 108}px;left:${scale * -5}px;top:${scale * 12}px;background-image: url(${handImg});`"/>
</div>
</template>
<script>
let total = 21;
let picHost = 'https://h2.appsimg.com/a.appsimg.com/upload/wxadmin/2021/12/09/153/9d7796ca49dd4165a6453b6cf4996fdb.png';
export default {
name: 'RebbitView',
props: {
// 缩放比例
scale: {
type: Number,
default: 1
},
// 等级
userLevel: {
type: Number,
default: 1
}
},
data () {
return {
isShowRabbit: true,
handImg: 'https://weixin.vipstatic.com/uploadfiles/wx-small/images/rubbit_hand_1.png'
};
},
watch: {
userLevel (value) {
let userLevel = value || 1;
this.handImg = `https://weixin.vipstatic.com/uploadfiles/wx-small/images/rubbit_hand_${userLevel}.png`;
}
},
mounted () {
this.startRubbit();
},
destroyed () {
this.stopRubbit();
},
methods: {
startRubbit () {
if (this.hasRubbit) {
return;
}
this.hasRubbit = true;
let canvas = this.$refs.rabbitId;
canvas.width = 270;
canvas.height = 300;
let context = canvas.getContext('2d');
this.getImage().then((img) => {
let startTime;
let curCount = 0;
this.step = () => {
if (!this.hasRubbit) {
return;
}
if (!startTime) {
startTime = new Date().getTime();
}
let timestamp = new Date().getTime();
let elapsed = timestamp - startTime;
if (elapsed > 40) {
startTime = timestamp;
let imgW = 270;
let imgH = 300;
let sx = (curCount % 3) * imgW;
let sy = Math.floor(curCount / 3) * imgH;
context.clearRect(0, 0, imgW, imgH);
context.drawImage(img, sx, sy, imgW, imgH, 0, 0, imgW, imgH); // 绘制
curCount = (curCount + 1) % total;
}
this.requestFrameId = requestAnimationFrame(this.step);
};
this.requestFrameId = requestAnimationFrame(this.step);
}).catch(err => {
console.error('加载兔子图片有异常', err);
this.isShowRabbit = false;
this.stopRubbit();
});
},
/**
* 获取图片对象
*/
getImage () {
return new Promise((resolve, reject) => {
let img = new Image();
img.src = picHost;
img.onerror = (err) => {
reject(err);
};
img.onload = () => {
resolve(img);
};
});
},
/**
* 停止动画
*/
stopRubbit () {
this.hasRubbit = false;
if (this.requestFrameId) {
cancelAnimationFrame(this.requestFrameId);
}
}
}
};
</script>
.rabiit_ll {
position: relative;
.hand_view {
position: absolute;
background-size: 100% 100%;
background-repeat: no-repeat;
animation: shake 1s infinite linear;
transform-origin: 50% 50%;
}
}
@keyframes shake {
0% {
transform: rotate(0deg);
}
25% {
transform: rotate(5deg);
}
50% {
transform: rotate(0deg);
}
75% {
transform: rotate(-5deg);
}
100% {
transform: rotate(0deg);
}
}

image.png
网友评论