Canvas createImageData() 方法

定义和用法

createImageData() 方法创建新的空白 ImageData 对象。新对象的默认像素值 transparent black。

对于 ImageData 对象中的每个像素,都存在着四方面的信息,即 RGBA 值:

  • R - 红色 (0-255)
  • G - 绿色 (0-255)
  • B - 蓝色 (0-255)
  • A - alpha 通道 (0-255; 0 是透明的,255 是完全可见的)

因此 ,transparent black 表示 (0,0,0,0)。

color/alpha 以数组形式存在,并且既然数组包含了每个像素的四条信息,数组的大小是 ImageData 对象的四倍。(获得数组大小有更简单的办法,就是使用 ImageDataObject.data.length)

包含 color/alpha 信息的数组存储于 ImageData 对象的 data 属性中。

提示:在操作完成数组中的 color/alpha 信息之后,您可以使用 putImageData() The method copies the image data back to the canvas.

Example:

This syntax changes 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;

This syntax changes the second pixel of the ImageData object to red:

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

Example

Create an ImageData object of 100*100 pixels, where each pixel is red, and then put it on the canvas:

Your browser does not support the HTML5 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

There are two versions of the createImageData() method:

1. Create a new ImageData object with the specified size (in pixels):

var imgData=context.createImageData(width,height;

2. Create a new ImageData object with the same size as the specified another ImageData object (without copying image data):

var imgData=context.createImageData(imageData;

Parameter value

Parameter Description
width The width of the ImageData object, in pixels.
height The height of the ImageData object, in pixels.
imageData Another ImageData object.

Υποστήριξη προγράμματος περιήγησης

Οι αριθμοί στην τάβλη αναφέρουν την έκδοση του πρώτου προγράμματος περιήγησης που υποστηρίζει αυτήν την ιδιότητα.

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

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