HTML Canvas Image Color Gray scale

Description

HTML Canvas Image Color Gray scale

View in separate window

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Grayscale</title>
  </head>  
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>

    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d');

      //draw some stripes: red, green, and blue
      for (var i = 0; i < canvas.width; i += 10) {
        for (var j = 0; j < canvas.height; j += 10) {
          context.fillStyle = (i % 20 === 0) ? "#f00" : ((i % 30 === 0) ? "#0f0" : "#00f");
          context.fillRect(i, j, 10, 10);
        }/*from  w  ww. ja v a 2  s .c  o  m*/
      }

      var imagedata = context.getImageData(0, 0, canvas.width, canvas.height),
          pixels = imagedata.data;

      //pixel iteration
      for (var offset = 0, len = pixels.length; offset < len; offset += 4) {
        var r = pixels[offset],
            g = pixels[offset + 1],
            b = pixels[offset + 2],
            y = (0.2126 * r) + (0.7152 * g) + (0.0722 * b); //relative luminance, humans perceive green more

        pixels[offset] = pixels[offset + 1] = pixels[offset + 2] = y;
      }

      context.putImageData(imagedata, 0, 0);
    };
    </script>
  </body>
</html>



PreviousNext

Related