Осталось символов: 2048
Комментариев больше нет


index.html
<!DOCTYPE html>
<html>
<head>
<title>Animation Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="src/styles.css" />
</head>
<body>
<div>
<canvas id="canvas"></canvas>
<script src="src/script.js"></script>
</div>
</body>
</html>
script.js
const startRecording = () => {
const canvas = document.querySelector("#canvas");
const data = []; // here we will store our recorded media chunks (Blobs)
const stream = canvas.captureStream(30); // records the canvas in real time at our preferred framerate 30 in this case.
const mediaRecorder = new MediaRecorder(stream); // init the recorder
// whenever the recorder has new data, we will store it in our array
mediaRecorder.ondataavailable = (e) => data.push(e.data);
// only when the recorder stops, we construct a complete Blob from all the chunks
mediaRecorder.onstop = (e) =>
downloadVideo(new Blob(data, { type: "video/webm;codecs=h264" }));
mediaRecorder.start();
setTimeout(() => {
mediaRecorder.stop();
}, 6000); // stop recording in 6s
};
const downloadVideo = async (blob) => {
const div = document.querySelector("div");
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "test.webm";
a.className = "button";
a.innerText = "click here to download";
div.appendChild(a);
};
// animation code...
startRecording();
animate();
const canvas = document.querySelector("#canvas");
setTimeout(() => {
rec.stop();
}, 10); // stop recording in 10s
rec.onstop = (e) =>
downloadVideo(new Blob(chunks, { type: "video/webm;codecs=h264" }));
Автоматическая загрузка записи в виде webm-файла.
Используя javascript, мы можем легко загрузить нашу запись в виде WebM файла: бесплатного формата медиафайлов, предназначенного для Интернета.WebM воспроизводится практически во всех основных браузерах.const exportVid(blob) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.style = "display: none";
a.href = url;
a.download = "recording.webm";
document.body.appendChild(a);
a.click();
}
Конвертировать видео в mp4 с помощью ffmpeg.wasm в JavaScript
MediaRecorder не способен обрабатывать запись в mp4 в Chrome или safari (по состоянию на 2022 год), но ffmpeg.wasm - это опция, которая позволяет конвертировать webm в mp4 внутри браузера.В onstop нашей функции startRecording мы можем передать наш большой двоичный объект этой exportVid функции, которая преобразует наш большой двоичный объект в mp4 перед его загрузкой.import { createFFmpeg, fetchFile } from "@ffmpeg/ffmpeg";
const ffmpeg = createFFmpeg({
corePath: "https://unpkg.com/@ffmpeg/core@0.11.0/dist/ffmpeg-core.js",
log: true,
});
const exportVid = async (blob) => {
if (!ffmpeg.isLoaded()) {
await ffmpeg.load();
ffmpeg.FS("writeFile", "test.avi", await fetchFile(blob));
await ffmpeg.run("-i", "test.avi", "test.mp4");
const data = ffmpeg.FS("readFile", "test.mp4");
const url = URL.createObjectURL(
new Blob([data.buffer], { type: "video/mp4" })
);
const a = document.createElement("a");
a.style = "display: none";
a.href = url;
a.download = "recording.webm";
document.body.appendChild(a);
a.click();
}
};
Поделиться записью с помощью Web Share API
Большинство устройств и браузеров могут обмениваться ссылками и файлами с помощью navigator.share() метода Web Share APIБазовая реализация этого в react заключалась бы в: const exportVid = async (blob) => {
await ffmpeg.run("-i", "test.avi","test.mp4");
const data = ffmpeg.FS("readFile", "test.mp4");
setVideoSrc(URL.createObjectURL(new Blob([data.buffer], { type: "video/mp4" })))
<button onClick={onShare}>share!</button>
const onShare = async () => {
if (!videoSrc) return;
const blob = await fetch(videoSrc).then((response) => response.blob());
const file = new File([blob], "test.mp4", { type: "video/mp4" });
const filesArray = [file];
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
await navigator.share({
files: filesArray,
});
}
};
Глоссарий:
Комментариев больше нет