<template>
<div style="background: red; padding: 20px">
<video ref="videoEl" src="/movie.mp4"></video>
<hr />
<canvas ref="canvasEl"></canvas>
<hr />
<button @click="videoPlay">播放</button>
<button @click="videoPause">暂停</button>
<button @click="videoStop">停止</button>
</div>
</template>
<script>
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
name: "VideoPage",
setup() {
/** @type {import("vue").Ref<HTMLVideoElement>} */
const videoEl = ref();
/** @type {import("vue").Ref<HTMLCanvasElement>} */
const canvasEl = ref();
onMounted(() => {
videoEl.value.addEventListener("canplay", function () {
canvasEl.value.width = videoEl.value.videoWidth;
canvasEl.value.height = videoEl.value.videoHeight;
const ctx = canvasEl.value.getContext("2d");
cancelAnimationFrame(window.animationFrameId);
function canvasRender() {
// 将video绘制到canvas
ctx.drawImage(videoEl.value, 0, 0);
// 在canvas中抠除指定颜色
const imageData = ctx.getImageData(
0,
0,
canvasEl.value.width,
canvasEl.value.height
);
// rgba
for (let i = 0; i < imageData.data.length; i += 4) {
if (
imageData.data[i] > 100 &&
imageData.data[i + 1] > 100 &&
imageData.data[i + 2] > 100
) {
imageData.data[i + 3] = 0;
}
}
ctx.putImageData(imageData, 0, 0);
window.animationFrameId = requestAnimationFrame(canvasRender);
}
canvasRender();
});
});
const videoPlay = () => {
videoEl.value.play();
};
const videoPause = () => {
videoEl.value.pause();
};
const videoStop = () => {
videoEl.value.load();
};
return {
videoEl,
canvasEl,
videoPlay,
videoPause,
videoStop,
};
},
});
</script>
<style scoped></style>