HTML5 Game - Inverting video colors

Introduction

We can do pixel manipulations on videos.

The following code inverts the colors of a short video clip.

WARNING

This recipe must be run on a web server due to security constraints with the getImageData() method.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> 
<html>
    <head>
        <script>
window.requestAnimFrame = (function(callback){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||// w w  w .  ja va2  s . c o m
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setTimeout(callback, 1000 / 60);
    };
})();

function drawFrame(canvas, context, video){
    context.drawImage(video, 0, 0);
    
    let imageData = context.getImageData(0, 0, canvas.width, canvas.height);
    let data = imageData.data;
    
    for (let i = 0; i < data.length; i += 4) {
        data[i] = 255 - data[i]; // red
        data[i + 1] = 255 - data[i + 1]; // green
        data[i + 2] = 255 - data[i + 2]; // blue
        // i+3 is alpha (the fourth element)
    }
    
    // overwrite original image
    context.putImageData(imageData, 0, 0);
    
    requestAnimFrame(function(){
        drawFrame(canvas, context, video);
    });
}

window.onload = function(){
    let canvas = document.getElementById("myCanvas");
    let context = canvas.getContext("2d");
    let video = document.getElementById("myVideo");
    drawFrame(canvas, context, video);
};
        </script>
    </head>
    <body>
        <video id="myVideo" autoplay="true" loop="true">
            <source src="http://java2s.com/style/demo/your.webm" type="video/webm"/>
        </video>
        <canvas id="myCanvas" width="640" height="360" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

We can perform pixel manipulations on video via the getImageData() method.

Related Topic