Created
October 5, 2018 23:18
-
-
Save benjaminadk/50b9e83bdd512cb5c3dbe1e5d4ef5ae3 to your computer and use it in GitHub Desktop.
Takes a incoming stream and creates a snapshot image using canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Earlier in your code | |
var canvas = document.createElement('canvas') | |
var ctx = canvas.getContext('2d') | |
// Capture a stream and this function will create a snapshot | |
function captureSnapshot(stream) { | |
// Create a video element and style it so it is way off the screen | |
var video = document.createElement('video') | |
video.style.cssText = 'position: absolute; left: -10000px; top: -10000px;' | |
// Add a define a function that responds to the 'loadedmetadata' event | |
// drawImage takes a video element, the coordinates to start drawing at, and the width and height of the drawing | |
// After we have snapshot in canvas remove video and stop stream | |
video.onloadedmetadata = () => { | |
canvas.width = video.videoWidth | |
canvas.height = video.videoHeight | |
ctx.drawImage(video, 0, 0, canvas.width, canvas.height) | |
video.remove() | |
stream.getTracks().forEach(track => track.stop()) | |
} | |
// Assign source to a URL created from the stream | |
video.src = window.URL.createObjectURL(stream) | |
// Append the video to the DOM | |
document.body.appendChild(video) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment