HTML Canvas - Data Property



The HTML Canvas data property of ImageData interface returns an array containing all the pixel data of the ImageData object.

The data is stored in the one-dimensional array in RGBA color order and is accessed by the context object when applying color to the graphics rendered on the Canvas element.

Possible input values

It returns a single dimensional array containing pixel data of the object in RGBA color order with values between 0 and 255 (both inclusive).

Example 1 − (Getting data length from console and window alert)

The following example creates a simple ImageData object and gets its length and array data using console and window alert.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="500" height="400" style="border: 1px solid black; "></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var imgdata = new ImageData(55, 55);
      window.alert('data length : ' + imgdata.data.length);
      console.log('data length : ' + imgdata.data.length);
   </script>
</body>
</html>

Output

The output returned by the above code on the webpage as −

HTML Canvas Data Property

The output returned by the window alert is −

HTML Canvas Data Property

The output returned by the console is −

HTML Canvas Data Property

Example

The following example draws a simple rgba pattern using the data property on the Canvas element by using the image object created first.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black; "></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var imgdata = new ImageData(200, 150);
      for (let i = 0; i < imgdata.data.length; i += 4) {
         imgdata.data[i + 0] = 122;
         imgdata.data[i + 1] = 255;
         imgdata.data[i + 2] = 144;
         imgdata.data[i + 3] = 100;
      }
      context.putImageData(imgdata, 25, 25);
   </script>
</body>
</html>

Output

The output returned by the image on the webpage as −

HTML Canvas Data Property
html_canvas_images.htm
Advertisements