无论autoplay
为真还是假,以下代码在Firefox上都可以正常工作,但在Chromium上不行。我该怎么修理它?
编辑1:我发现我可以从autoplay = true
开始,然后在onloadeddata
暂停视频到video.pause()
。
编辑2:另一件有趣的事情被发现。您可以将video.currentTime
设置为,例如5,以捕获第五秒,如果视频的持续时间小于,再次例如5秒,则最后一帧将绘制在画布上。然后你可以在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>