Ενότητα δεδομένων του Canvas

Ορισμός και χρήση

data Η ιδιότητα επιστρέφει έναν αντικείμενο που περιέχει τα δεδομένα εικόνας του καθορισμένου αντικειμένου ImageData.

Για κάθε πιξέλ του αντικειμένου ImageData, υπάρχουν τέσσερις πτυχές πληροφοριών, δηλαδή οι τιμές 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 for more information about the ImageData object.

Example

Create an ImageData object of 100x100 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 < imageData.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

Σημείωση:O Internet Explorer 8 και οι προηγούμενες εκδόσεις δεν υποστηρίζουν το στοιχείο <canvas>.