YouTip LogoYouTip

Met Canvas Createimagedata

[![Image 1: Canvas Object Reference](#) Canvas Object](#) ## Example Create a 100*100 pixel ImageData object where every pixel is red, then place it on the canvas: YourbrowserdoesnotsupporttheHTML5canvastag. 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 Β»](#) * * * ## Browser Support ![Image 2: Internet Explorer](#)![Image 3: Firefox](#)![Image 4: Opera](#)![Image 5: Google Chrome](#)![Image 6: Safari](#) The createImageData() method is supported in Internet Explorer 9, Firefox, Opera, Chrome, and Safari. **Note:** Internet Explorer 8 and earlier versions do not support the element. * * * ## Definition and Usage The createImageData() method creates a new, blank ImageData object. The default pixel value for the new object is transparent black. For each pixel in the ImageData object, there are four pieces of information, the RGBA value: R - Red (0-255) G - Green (0-255) B - Blue (0-255) A - Alpha channel (0-255; 0 is transparent, 255 is fully visible) Therefore, transparent black is (0,0,0,0). The color/alpha information is stored in an array, and since the array contains four pieces of information for each pixel, the array size is four times the ImageData object's size: width*height*4. (A simpler way to get the array size is to use the ImageDataObject.data.length property.) The array containing the color/alpha information is stored in the (#) property of the ImageData object. **Tip:** After manipulating the color/alpha information in the array, you can use the [putImageData()](#) method to copy the image data back to the canvas. **Example:** Syntax to make the first pixel in the ImageData object red: imgData=ctx.createImageData(100,100); imgData.data=255; imgData.data=0; imgData.data=0; imgData.data=255; Syntax to make the second pixel in the ImageData object green: imgData=ctx.createImageData(100,100); imgData.data=0; imgData.data=255; imgData.data=0; imgData.data=255; * * * ## JavaScript Syntax There are two versions of the createImageData() method: 1. Create a new ImageData object with specified dimensions (in pixels): | JavaScript Syntax: | var imgData=_context_.createImageData(_width,height_); | | --- | 2. Create a new ImageData object with the same dimensions as another specified ImageData object (does not copy the image data): | JavaScript Syntax: | var imgData=_context_.createImageData(_imageData_); | | --- | ## Parameter Values | Parameter | Description | | --- | --- | | _width_ | The width of the ImageData object, in pixels. | | _height_ | The height of the ImageData object, in pixels. | | _imageData_ | Another ImageData object. | * * Canvas Object](#)
← Met Canvas GetimagedataProp Canvas Imagedata Data β†’