Skip to content

Instantly share code, notes, and snippets.

@bbg
Created February 9, 2020 13:05
Show Gist options
  • Select an option

  • Save bbg/72c3c0627752931b97a9ba6c3f673cfc to your computer and use it in GitHub Desktop.

Select an option

Save bbg/72c3c0627752931b97a9ba6c3f673cfc to your computer and use it in GitHub Desktop.
Canvas Stream Capture
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
div {
display: block;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
const ctx = canvas.getContext('2d');
var x = 0;
animate();
startRecording();
function startRecording() {
const chunks = [];
const stream = canvas.captureStream();
const record = new MediaRecorder(stream);
record.ondataavailable = event => chunks.push(event.data);
record.onstop = event => exportVideo(new Blob(chunks, { type: 'video/webm' }));
record.start();
setTimeout(() => record.stop(), 3000);
}
function exportVideo(blob) {
const video = document.createElement('video');
video.src = URL.createObjectURL(blob);
video.controls = true;
document.body.appendChild(video);
const downloadLink = document.createElement('a');
downloadLink.download = 'myvid.webm';
downloadLink.href = video.src;
downloadLink.textContent = 'download the video';
document.body.appendChild(downloadLink);
}
function animate(){
x = (x + 1) % canvas.width;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width,canvas.height);
ctx.fillStyle = 'black';
ctx.fillRect(x - 20, 0, 40, 40);
requestAnimationFrame(animate);
}
})
</script>
</head>
<body>
<div>
<canvas id="canvas" width="160" height="96"></canvas>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment