ImageData.data - Web APIs 编辑

The readonly ImageData.data property returns a Uint8ClampedArray that contains the ImageData object's pixel data. Data is stored as a one-dimensional array in the RGBA order, with integer values between 0 and 255 (inclusive).

Syntax

imageData.data

Examples

Getting an ImageData object's pixel data

This example creates an ImageData object that is 100 pixels wide and 100 pixels tall, making 10,000 pixels in all. The data array stores four values for each pixel, making 4 x 10,000, or 40,000 values in all.

let imageData = new ImageData(100, 100);
console.log(imageData.data);         // Uint8ClampedArray[40000]
console.log(imageData.data.length);  // 40000

Filling a blank ImageData object

This example creates and fills a new ImageData object with colorful pixels.

HTML

<canvas id="canvas"></canvas>

JavaScript

Since each pixel consists of four values within the data array, the for loop iterates by multiples of four. The values associated with each pixel are R (red), G (green), B (blue), and A (alpha), in that order.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.createImageData(100, 100);

// Iterate through every pixel
for (let i = 0; i < imageData.data.length; i += 4) {
  // Percentage in the x direction, times 255
  let x = (i % 400) / 400 * 255;
  // Percentage in the y direction, times 255
  let y = Math.ceil(i / 400) / 100 * 255;

  // Modify pixel data
  imageData.data[i + 0] = x;        // R value
  imageData.data[i + 1] = y;        // G value
  imageData.data[i + 2] = 255 - x;  // B value
  imageData.data[i + 3] = 255;      // A value
}

// Draw image data to the canvas
ctx.putImageData(imageData, 20, 20);

Result

More examples

For more examples using ImageData.data, see Pixel manipulation with canvas, CanvasRenderingContext2D.createImageData(), and CanvasRenderingContext2D.putImageData().

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'ImageData.data' in that specification.
Living StandardInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:81 次

字数:5261

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文