HTML5 Canvas Tutorial - HTML5 Canvas Image Data








To get the image data for each pixel of a rectangular area, we can get the image data object with the getImageData().

The pixel data is accessible from the data property.

Each pixel in the image data contains four components, a red, green, blue, and alpha component.

We can access the pixel data from the image data object by iterating over all of the pixels starting from the top left corner to the bottom right corner of the region

We can also access pixel data based on x, y coordinates.

The following code shows how to iterate over all pixels

var imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight);
var data = imageData.data;

// iterate over all pixels
for(var i = 0, n = data.length; i < n; i += 4) {
  var red = data[i];
  var green = data[i + 1];
  var blue = data[i + 2];
  var alpha = data[i + 3];
}

The following code shows how to pick out pixel data from x, y coordinate.

var imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight);
var data = imageData.data;

// pick out pixel data from x, y coordinate
var x = 20;
var y = 20;
var red = data[((imageWidth * y) + x) * 4];
var green = data[((imageWidth * y) + x) * 4 + 1];
var blue = data[((imageWidth * y) + x) * 4 + 2];
var alpha = data[((imageWidth * y) + x) * 4 + 3];

        

The following code shows how to iterate over all pixels based on x and y coordinates.

var imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight);
var data = imageData.data;

// iterate over all pixels based on x and y coordinates
for(var y = 0; y < imageHeight; y++) {
  // loop through each column
  for(var x = 0; x < imageWidth; x++) {
    var red = data[((imageWidth * y) + x) * 4];
    var green = data[((imageWidth * y) + x) * 4 + 1];
    var blue = data[((imageWidth * y) + x) * 4 + 2];
    var alpha = data[((imageWidth * y) + x) * 4 + 3];
  }
}

The following code displays an image.


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="400"></canvas>
    <script>
      function drawImage(imageObj) {<!--from w  w  w.ja va 2  s  . co m-->
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var imageX = 70;
        var imageY = 50;
        var imageWidth = imageObj.width;
        var imageHeight = imageObj.height;

        context.drawImage(imageObj, imageX, imageY);

      }
      var imageObj = new Image();
      imageObj.onload = function() {
        drawImage(this);
      };
      imageObj.src = 'http://www.java2s.com/style/demo/border.png';

    </script>
  </body>
</html>      

The code above is rendered as follows:





Invert Image Colors

To invert the image colors, we can invert the red, green, and blue components by subtracting each component from the max color value, 255.

Next, we can redraw the inverted image using the updated image data with the putImageData() method.

The putImageData() method requires an image data array and a position


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="400"></canvas>
    <script>
      function drawImage(imageObj) {<!--from w w w. jav  a 2s  .  c  o  m-->
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var x = 69;
        var y = 50;

        context.drawImage(imageObj, x, y);

        var imageData = context.getImageData(x, y, imageObj.width, imageObj.height);
        var data = imageData.data;

        for(var i = 0; i < data.length; i += 4) {
          // red
          data[i] = 255 - data[i];
          // green
          data[i + 1] = 255 - data[i + 1];
          // blue
          data[i + 2] = 255 - data[i + 2];
        }

        // overwrite original image
        context.putImageData(imageData, x, y);
      }
      
      var imageObj = new Image();
      imageObj.onload = function() {
        drawImage(this);
      };
      imageObj.src = 'http://www.java2s.com/style/demo/border.png';
    </script>
  </body>
</html>      

The code above is rendered as follows:





Grayscale Image Colors

To grayscale an image, we can calculate the brightness of each pixel, and then set the red, green, and blue components equal to the brightness.


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="400"></canvas>
    <script>
      function drawImage(imageObj) {<!--from ww  w . j  a  v a  2s  .  co m-->
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var x = 70;
        var y = 50;

        context.drawImage(imageObj, x, y);

        var imageData = context.getImageData(x, y, imageObj.width, imageObj.height);
        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];
          // red
          data[i] = brightness;
          // green
          data[i + 1] = brightness;
          // blue
          data[i + 2] = brightness;
          console.log(brightness);
        }
        // overwrite original image
        context.putImageData(imageData, x, y);
      }
      
      var imageObj = new Image();
      imageObj.onload = function() {
        drawImage(this);
      };
      imageObj.src = 'http://www.java2s.com/style/demo/border.png';
    </script>
  </body>
</html>      

The code above is rendered as follows:

Image Data URL

To get the image data URL, we can use the toDataURL() which converts the canvas drawing into a 64 bit encoded PNG URL.

To get the image data URL in the jpeg format, we can pass image/jpeg as the first argument in the toDataURL() method.

To control the image quality for a jpeg image, you can pass in a number from 0 to 1 as the second argument to the toDataURL() method.


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
<!--  ww w .  ja va 2 s  .  co  m-->
      // draw cloud
      context.beginPath();
      context.moveTo(170, 80);
      context.bezierCurveTo(130, 100, 130, 150, 230, 150);
      context.bezierCurveTo(250, 180, 320, 180, 340, 150);
      context.bezierCurveTo(420, 150, 420, 120, 390, 100);
      context.bezierCurveTo(430, 40, 370, 30, 340, 50);
      context.bezierCurveTo(320, 5, 250, 20, 250, 50);
      context.bezierCurveTo(200, 5, 150, 20, 170, 80);
      context.closePath();
      context.lineWidth = 5;
      context.fillStyle = 'red';
      context.fill();
      context.strokeStyle = '#0000ff';
      context.stroke();

      // save canvas image as data url (png format by default)
      var dataURL = canvas.toDataURL();
      console.log(dataURL);
   
    </script>
  </body>
</html>      

The code above is rendered as follows:

Load Image Data URL

The following code fills the data url to a new created image object.


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
<!--from   w  ww.  j  a v a2s.com-->
      // draw cloud
      context.beginPath();
      context.moveTo(170, 80);
      context.bezierCurveTo(130, 100, 130, 150, 230, 150);
      context.bezierCurveTo(250, 180, 320, 180, 340, 150);
      context.bezierCurveTo(420, 150, 420, 120, 390, 100);
      context.bezierCurveTo(430, 40, 370, 30, 340, 50);
      context.bezierCurveTo(320, 5, 250, 20, 250, 50);
      context.bezierCurveTo(200, 5, 150, 20, 170, 80);
      context.closePath();
      context.lineWidth = 5;
      context.fillStyle = 'red';
      context.fill();
      context.strokeStyle = '#0000ff';
      context.stroke();

      // save canvas image as data url (png format by default)
      var dataURL = canvas.toDataURL();
      console.log(dataURL);
      
      // load image from data url
      var imageObj = new Image();
      imageObj.onload = function() {
          // scale y component
          context.scale(1, 0.5);
          context.drawImage(this, 0, 0);
      };

      imageObj.src = dataURL;      
    </script>
  </body>
</html>   

The code above is rendered as follows:

Save Canvas as image

We can save canvas to an image URL and then assign the URL to an img element.


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="578" height="200" style="display:none;"></canvas>
    <img id="canvasImg" alt="Right click to save me!">
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
<!--from   w w  w .jav  a  2 s  .  c om-->
      // draw cloud
      context.beginPath();
      context.moveTo(170, 80);
      context.bezierCurveTo(130, 100, 130, 150, 230, 150);
      context.bezierCurveTo(250, 180, 320, 180, 340, 150);
      context.bezierCurveTo(420, 150, 420, 120, 390, 100);
      context.bezierCurveTo(430, 40, 370, 30, 340, 50);
      context.bezierCurveTo(320, 5, 250, 20, 250, 50);
      context.bezierCurveTo(200, 5, 150, 20, 170, 80);
      context.closePath();
      context.lineWidth = 5;
      context.fillStyle = 'red';
      context.fill();
      context.strokeStyle = 'black';
      context.stroke();

      // save canvas image as data url (png format by default)
      var dataURL = canvas.toDataURL();

      // set canvasImg image src to dataURL so it can be saved as an image
      document.getElementById('canvasImg').src = dataURL;

    </script>
  </body>
</html>      

The code above is rendered as follows: