HTML Canvas Image convert colors to grayscale

Introduction

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

View in separate window

<!DOCTYPE HTML> 
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                //from w ww  .  ja  v a  2 s  . c  o  m
                var imageObj = new Image();
                imageObj.onload = function(){
                    var sourceWidth = this.width;
                    var sourceHeight = this.height;
                    var destX = canvas.width / 2 - sourceWidth / 2;
                    var destY = canvas.height / 2 - sourceHeight / 2;
                    var sourceX = destX;
                    var sourceY = destY;
                    
                    context.drawImage(this, destX, destY);
                    
                    var imageData = context.getImageData(sourceX, sourceY, sourceWidth, sourceHeight);
                    var data = imageData.data;
                    
                    for (var i = 0; i < data.length; i += 4) {
                        var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
                        
                        data[i] = brightness; // red
                        data[i + 1] = brightness; // green
                        data[i + 2] = brightness; // blue
                        // i+3 is alpha (the fourth element)
                    }
                    
                    // overwrite original image
                    context.putImageData(imageData, destX, destY);
                };
                imageObj.src = "image1.png";
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>



PreviousNext

Related