This JavaScript program demonstrates how to capture video content from a canvas element and display it in a video element. The canvas flashes colors to generate capturable content. After 5 seconds of recording, the captured video can be played.
<!DOCTYPE html>
<html>
<head>
<title>XoaX.net's Javascript</title>
<script type="text/javascript" src="VideoCaptureAndDisplay.js"></script>
</head>
<body onload="Initialize()">
<canvas width="300" height="225"></canvas>
<video autoplay controls></video>
</body>
</html>var gqCanvasElement = null;
var gqContext = null;
var gqVideoElement = null;
var giColorIndex = 0;
var saColorNames = ["red", "white", "blue"];
var qaVideoChunks = [];
var giIntervalId = 0;
function Initialize() {
gqCanvasElement = document.querySelector("canvas");
gqContext = gqCanvasElement.getContext("2d");
gqVideoElement = document.querySelector("video");
var qVideoStream = gqCanvasElement.captureStream(30);
var qMediaRecorder = new MediaRecorder(qVideoStream);
// Set a callback to add the data to the chunk array.
qMediaRecorder.ondataavailable = function(qEvent) {
console.log("dataavailable");
console.log("datasize = " + qEvent.data.size);
qaVideoChunks.push(qEvent.data);
};
// Turn the chunks into a Blob and create a URL for it.
qMediaRecorder.onstop = function(e) {
console.log("stopped");
var qBlob = new Blob(qaVideoChunks, { type : "video/mp4" });
var sVideoURL = URL.createObjectURL(qBlob);
console.log("URL = " + sVideoURL);
gqVideoElement.src = sVideoURL;
};
// Start drawing different colors to the screen every 1/5th of a second (200 milliseconds).
giIntervalId = setInterval(DrawNext, 200);
// Start recording the animation.
qMediaRecorder.start();
// Stop the recording and animation after 5 seconds.
setTimeout(function (){
qMediaRecorder.stop();
// Stop the animation
clearInterval(giIntervalId);
}, 5000);
}
function DrawNext(){
// Alternate the colors by changing the color index.
giColorIndex = ((giColorIndex + 1) % saColorNames.length);
gqContext.fillStyle = saColorNames[giColorIndex];
gqContext.fillRect(0, 0, gqCanvasElement.width, gqCanvasElement.height);
}
© 20072025 XoaX.net LLC. All rights reserved.