以下代码在 Firefox 上运行良好,无论 autoplay
为 true 或 false,但在 Chromium 上则不然。我该如何修复它?
编辑1:我发现我可以从autoplay = true
开始,然后在onloadeddata
中使用video暂停视频.pause()
.
编辑2:发现了另一个有趣的事情。您可以将 video.currentTime
设置为(例如 5)以捕获第 5 秒,如果视频的持续时间小于(例如 5 秒),则最后一帧将绘制在 Canvas 上。然后您可以在onloadeddata
事件中将其设置回零。这很好,因为在大多数情况下,第一秒是黑色的。
let inputFile = document.getElementById("files");
let container = document.getElementById("container");
inputFile.addEventListener("change", inputFileEventHandler);
function inputFileEventHandler() {
for (const file of inputFile.files) {
let canvas = document.createElement("canvas");
canvas.style.border = "1px solid gray";
canvas.style.padding = "16px";
let video = document.createElement("video");
video.style.width = "250px";
video.style.height = "auto";
video.style.border = "1px solid gray";
video.style.padding = "16px";
video.autoplay = false;
video.src = URL.createObjectURL(file);
container.append(video);
container.append(canvas);
video.onloadeddata = () => {
canvas.getContext("2d").drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
}
}
}
<!DOCTYPE html>
<html>
<body>
<input type="file" id="files" name="files" multiple>
<div id="container"></div>
</body>
</html>
最佳答案
我不知道问题是什么
似乎 preload: auto
有帮助,但我不确定
同时处理多个事件可以使其工作,但并不总是如此
let inputFile = document.getElementById("files");
let container = document.getElementById("container");
inputFile.addEventListener("change", inputFileEventHandler);
const events = `abort
canplay
canplaythrough
durationchange
loadeddata
suspend`.split('\n')
function inputFileEventHandler() {
for (const file of inputFile.files) {
const video = document.createElement("video");
video.style.width = "250px";
video.style.height = "auto";
video.style.border = "1px solid gray";
video.style.padding = "16px";
video.autoplay = false;
video.preload = 'auto';
video.src = URL.createObjectURL(file);
container.append(video);
for (const event of events) {
const canvas = document.createElement("canvas");
canvas.style.border = "1px solid gray";
canvas.style.padding = "16px";
container.append(canvas);
video.addEventListener(event, () => {
console.log(event)
const ctx = canvas.getContext("2d")
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
ctx.font = "24px serif";
ctx.fillText(event, 10, 50);
})
}
}
}
<!DOCTYPE html>
<html>
<body>
<input type="file" id="files" name="files" multiple>
<div id="container"></div>
</body>
</html>
关于javascript - 当 Chromium 上的自动播放为 false 时,视频不会绘制在 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74749122/