重点在if (!canvas)
里面的最后一行,其他的稍微看看注释就明白了
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>BadApple</title>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript">
function renderVideoFrame(videoDom) {
var videoSize = {
width: parseFloat(videoDom.videoWidth),
height: parseFloat(videoDom.videoHeight),
};
var canvas = document.querySelector("#canvas");
if (!canvas) {
canvas = document.createElement("canvas");
canvas.id = "canvas";
canvas.style.width = videoDom.style.width;
canvas.style.height = videoDom.style.height;
canvas.style.position = "absolute";
canvas.style.zIndex = 1;
canvas.style.left = canvas.style.top = "0";
canvas.width = videoSize.width;
canvas.height = videoSize.height;
document.body.appendChild(canvas);
}
const ctx = canvas.getContext("2d");
ctx.drawImage(videoDom, 0, 0, videoSize.width, videoSize.height);
}
function init() {
var videoDom = document.createElement("video");
videoDom.src = "./bg.mov";
videoDom.style.width = "100vw";
videoDom.style.height = "100vh";
videoDom.muted = true;
videoDom.addEventListener("canplay", function () {
renderVideoFrame(videoDom);
videoDom.play();
startRender();
});
videoDom.addEventListener("ended", function () {
renderVideoFrame(videoDom);
videoDom.play();
startRender();
});
var timerId;
function startRender() {
timerId = requestAnimationFrame(updateRender);
}
function updateRender() {
renderVideoFrame(videoDom);
timerId = requestAnimationFrame(updateRender);
}
function stopRender() {
cancelAnimationFrame(timerId);
}
}
window.onload = function () {
init();
};
</script>
</head>
<body></body>
</html>