HTML Canvas - createImageData() Method



The HTML Canvas createImageData() method of Canvas 2D API creates an ImageData object in the Canvas element.

Syntax

Following is the syntax of HTML Canvas createImageData() method −

CanvasRenderingContext2D.createImageData(data, width, height);	

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1

width

The width value which is given to the ImageData object.

2

height

The width value which is passed to the ImageData object.

3

data

This data object is an existing ImageData object from which the properties such as width and height are copied into new object.

Return value

A new ImageData object is created with specified height and width. It is filled with transparent black pixels by default.

Example

The following example creates a blank ImageData object using the HTML Canvas createImageData() method and returns its values using 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="400" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var imgdata = context.createImageData(55, 55);
      console.log(imgdata);
   </script>
</body>
</html>

Output

The output returned by the image on the webpage as −

HTML Canvas CreateImageData Method

The data shown in the console as −

HTML Canvas CreateImageData Method

Example

The following example demonstrates how an Image data object is created and styled inside the Canvas element using the HTML Canvas createImageData() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body onload="Context();">
   <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
   <script>
      function Context() {
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d');
         var i, imageData = context.createImageData(100, 100);
         for (i = 0; i < imageData.data.length; i += 4) {
            imageData.data[i + 0] = 200;
            imageData.data[i + 1] = 100;
            imageData.data[i + 2] = 100;
            imageData.data[i + 3] = 200;
         }
         context.putImageData(imageData, 15, 15);
      }
   </script>
</body>
</html>
Output

The output returned by the image on the webpage as −

HTML Canvas CreateImageData Method
html_canvas_images.htm
Advertisements