Canvas Demo

Capturing screenshot using Canvas

by Shoaib Chikate

HTML

<div class="video">
    <video id="video" src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" muted controls autoplay></video>
</div>
<div class="timeline" id="timeline"></div>

CSS

body {
    background-color: #000;
    margin: 0;
}

/* video */

.video {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 30px;
    height: 200;
    overflow: hidden;
}
 
.video video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

/* timeline */

.timeline {
    overflow-x: scroll;
    white-space: nowrap;
    width: 100%;
    height:100px;
}

.timeline canvas {
    display: inline;
    width: 100px;
}

JavaScript

var timeline = document.getElementById('timeline'),
    video = document.getElementById('video'),
    interval = null;

video.addEventListener("playing", onStart);
video.addEventListener("pause", onStop);
video.addEventListener("ended", onEnd);

function onStart() {
	if (interval == null) {
		interval = window.setInterval(createImage, 1000);
	}
}

function onStop() {
	if (interval) {
		clearInterval(interval);
		interval = null;
	}
}

function onEnd() {
	onStop();
    video.removeEventListener("playing", onStart);
    video.removeEventListener("pause", onStop);
    video.removeEventListener("ended", onEnd);
}

function createImage() {
    console.log('createImage', video.currentTime, video.videoWidth, video.videoHeight);
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, video.videoWidth, 400);
    timeline.appendChild(canvas);
}