JavaScript canvas2d object method: createImageData()
[this page | pdf | back links]
The
createImageData() method of
the JavaScript
DOM object
returned by the getContext("2d")
method applied to the HTML <canvas>
element creates a new blank ImageData object.
Each pixel in the
ImageData has 4 values, i.e. its RGBA values (see CSS Colours). The data is
held in an array which is 4 times the size of the ImageData object, i.e. width
x height x 4. This is stored in the data
property of the ImageDataObject.
There are two versions of
the createImageData() method
with the following formats and parameters:
context.createImageData(width, height)
Parameter
|
Required / Optional
|
Description
|
width
|
Required
|
Width of ImageData, in
pixels
|
height
|
Required
|
Height of ImageData, in
pixels
|
context.createImageData(imageData)
Parameter
|
Required / Optional
|
Description
|
imageData
|
Required
|
ImageData object to be
used as a template for the new object (note only dimensions are used, the
image data is not copied
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span>
<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "60");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");
var imgData = c2.createImageData(100,20)
for (var i = 0; i<imgData.data.length; i += 4) {
imgData.data[i+0] = 255; //red channel
imgData.data[i+1] = 0;
imgData.data[i+2] = 0;
imgData.data[i+3] = 255;
}
c2.putImageData(imgData,60,20);
c2.strokeStyle = "rgba(0,0,255,40)"; //so partly transparent
c2.rect(30, 10, 100, 40);
c2.stroke();
document.getElementById("element").appendChild(x2);
</script>
</body>
</html>
|
FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvas2dCreateImageData() {
var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.createImageData;
} |
NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)