JSFiddle - React, Tailwind, and code Playground
by Jon-Carlos Rivera
HTML
<div id="container">
<div class="overlay">
Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello! Hello!
</div>
<video src="http://vjs.zencdn.net/v/oceans.mp4" width="600" controls crossorigin></video>
</div>
<canvas></canvas>
CSS
#container {
position: relative;
}
canvas { display: none; }
.overlay {
display: none;
position: absolute;
color: white;
border: 1px solid white;
}
JavaScript
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var overlay = document.querySelector('.overlay');
video.addEventListener('timeupdate', function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var quad = getQuadrant(video);
ctx.drawImage(video, 0, 0);
var videoData = ctx.getImageData(quad.x, quad.y, quad.videoWidth, quad.videoHeight);
if (video.currentTime >= 3 && video.currentTime <= 8) {
var averageColor = getPrimaryColor(videoData.data);
setOverlayVisible(rgbString(chooseColor(averageColor)), quad);
} else {
overlay.style.display = 'none';
}
});
function chooseColor (color) {
var brightness = (0.299 * color.red + 0.587 * color.green + 0.114 * color.blue);
var col = brightness > 127 ? 0 : 255;
return {
red: col,
green: col,
blue: col
};
}
function rgbString(color) {
return 'rgb(' + [color.red, color.green, color.blue].map(Math.floor).join(',') + ')';
}
function getPrimaryColor (pixels) {
var length = pixels.length;
var num = length / 4;
var pixel = 0;
var sumR = 0, sumG = 0, sumB = 0;
console.log(length);
while (pixel < length) {
var red = pixels[pixel++];
var green = pixels[pixel++];
var blue = pixels[pixel++];
pixel++; // alpha channel
sumR += red;
sumG += green;
sumB += blue;
}
return {
red: sumR / num,
green: sumG / num,
blue: sumB / num
};
}
function getQuadrant (video) {
return {
x: 0,
y: 0,
width: video.clientWidth / 2,
videoWidth: video.videoWidth / 2,
height: video.clientHeight / 2,
videoHeight: video.videoHeight / 2
};
}
function setOverlayVisible (color, quad) {
overlay.style.width = quad.width + 'px';
overlay.style.height = quad.height + 'px';
overlay.style.display = 'block';
overlay.style.color = color;
}