W3Schools.com

HTML5 canvas imagedata data Attribute

HTML5 track Tag Reference HTML5 canvas reference

Example

Create a 50*50 pixels imagedata object where every pixel is red:

Canvas

Yor browser does not support the canvas tag.

JavaScript:

var ctx=c.getContext("2d");
var imgData=ctx.createImageData(50,50);
for (i=0; i<imgData.width*imgData.height*4;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 »

Definition and Usage

The data attribute represents an array containing information of every pixel of an imagedata object.

For every pixel in the imagedata object there are 4 pieces of information, the rgba values:
1. The color red (0-255)
2. The color green (0-255)
3. The color blue (0-255)
4. The alpha strength (0-255) where 0 is transparent and 255 is fully visible

The information is held in an array, and since the array contains 4 pieces of information of every pixel, the array's size is 4 times the size of the rectangle: width*height*4.

You can change the information in the array, and put the new drawings back on the canvas, using the putImageData method.


JavaScript Syntax

JavaScript syntax: imageData.data[0]=255;

The syntax for making the first pixel in the imagedata object red:

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

The syntax for making the second pixel in the imagedata object green:

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


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The data attribute is supported in all major browsers.


Attribute Values

Values Description
array Specifies rgba values of the imagedata object


HTML5 track Tag Reference HTML5 canvas reference


WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE