The createImageData()
function store an individual pixel in memory.
by creating a new, blank ImageData
object.
The new created ImageData
object's pixel
values are transparent black by default.
Every pixel in an ImageData
object has four-element-array-like value, the RGBA values:
createImageData() |
Yes | Yes | Yes | Yes | Yes |
It has the following three formats.
imagedata = context.createImageData(sw, sh)
The sw and sh parameters represent the width and height values for the ImageData object.
For example, imagedata=createImageData(100,100)
would create a 100 x 100 area of memory in which to store pixel data.
imagedata = context.createImageData(imagedata)
The imagedata parameter represents a separate instance of ImageData. This constructor creates a new ImageData object with the same width and height as the parameter ImageData.
imagedata = context.createImageData()
returns a blank ImageData instance.
An ImageData object contains three attributes:
The following code sets the second element in the data array to 255, which create a green color.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from w ww .jav a 2 s . c om-->
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var imgData = ctx.createImageData(c.width, c.height);
for (var i = 0; i < imgData.data.length; i += 4) {
imgData.data[i+0] = 0;
imgData.data[i+1] = 255;
imgData.data[i+2] = 0;
imgData.data[i+3] = 255;
}
ctx.putImageData(imgData, 0, 0);
</script>
</body>
</html>
The code above is rendered as follows:
The following code get the ImageData object from canvas. Then it updates the color in each pixel to make a gradient color.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from w w w .j a va2s.c om-->
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var imageData = ctx.createImageData(c.width, c.height);
for(var i=0; i<imageData.width; i++) {
for(var j=0; j<imageData.height; j++) {
tmp = ((imageData.width * j) + i) * 4;
imageData.data[tmp] = 0;
imageData.data[tmp + 1] = 0;
imageData.data[tmp + 2] = 127*Math.sin(i/100)+128;
imageData.data[tmp + 3] = 255;
}
}
ctx.putImageData(imageData, 0, 0);
</script>
</body>
</html>
The code above is rendered as follows: