需求:后台会通过WebSocket每10毫秒返回一张base64的图片,如果直接使用el-image的话,图片切换的时候会出现不停的闪烁和卡顿问题,所以用canvas来解决这个问题
废话不多说,直接上例子组件
子组件
<template>
<canvas ref="canvas" :width="width" :height="height"></canvas>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
// 声明组件 Props
const props = defineProps({
base64Images: String, // 图片字符串
fps: Number, // 帧率
width: { type: Number, default: 400 }, // 画面宽度
height: { type: Number, default: 300 }, // 画面高度
});
// 使用 ref 创建响应式数据
const canvas = ref(null);
let currentFrame = 0;
let animationInterval = null;
// 在组件挂载后开始动画
onMounted(() => {
startAnimation();
});
// 在组件卸载前清除定时器
onUnmounted(() => {
stopAnimation();
});
// 监听 base64Images 变化,更新动画
watch(
() => props.base64Images,
(newValue, oldValue) => {
if (newValue !== oldValue) {
stopAnimation(); // 停止之前的动画
currentFrame = 0; // 重置当前帧索引
startAnimation(); // 开始新的动画
}
}
);
// 开始动画
const startAnimation = () => {
const frameDuration = 1000 / props.fps;
animationInterval = setInterval(renderFrame, frameDuration);
};
// 渲染每一帧
const renderFrame = () => {
const img = new Image();
img.onload = () => {
const ctx = canvas.value.getContext("2d");
ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
ctx.drawImage(img, 0, 0, props.width, props.height);
};
img.src = props.base64Images;
};
// 停止动画
const stopAnimation = () => {
clearInterval(animationInterval);
};
</script>
父组件使用
<canvasVideo :base64Images="cameraContinuous" :fps="25" :width="400" :height="400" />
import canvasVideo from './components/canvasVideo.vue'
//cameraContinuous 需要通过websocket不停获取后台推送图片
const cameraContinuous = ref('')