Propriété de données Canvas

Définition et utilisation

data La propriété retourne un objet contenant les données d'image de l'objet ImageData spécifié.

Pour chaque pixel de l'objet ImageData, il existe quatre types d'informations, à savoir les valeurs RGBA :

  • R - red (0-255)
  • G - green (0-255)
  • B - blue (0-255)
  • A - alpha channel (0-255; 0 is transparent, 255 is fully visible)

color/alpha exists as an array and is stored in the ImageData object's data in the property.

Example:

Syntax to change the first pixel of the ImageData object to red:

imgData = ctx.createImageData(100, 100);
imgData.data[0] = 255;
imgData.data[1] = 0;
imgData.data[2] = 0;
imgData.data[3] = 255;

Syntax to change the second pixel of the ImageData object to green:

imgData = ctx.createImageData(100, 100);
imgData.data[4] = 0;
imgData.data[5] = 255;
imgData.data[6] = 0;
imgData.data[7] = 255;

Tip:See createImageData(),getImageData() and putImageData() Methods to learn more about the ImageData object.

Example

Create an ImageData object of 100*100 pixels, with each pixel set to red:

Your browser does not support the canvas tag.

JavaScript:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var imgData = ctx.createImageData(100, 100);
for (var i = 0; i < imgData.data.length; i += 4)
  {
  imgData.data[i+0] = 255;
  imgData.data[i+1] = 0;
  imgData.data[i+2] = 0;
  imgData.data[i+3] = 255;
  }
ctx.putImageData(imgData, 10, 10);

Try it yourself

Syntax

imageData.data;

Browser support

Table numbers indicate the first browser version that fully supports this attribute.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

Remarque :Les versions 8 d'Internet Explorer et antérieures ne prennent pas en charge l'élément <canvas>.