JavaScript canvas2d object method: getImageData()
[this page | pdf | back links]
The getImageData() method of the JavaScript
DOM object
returned by the getContext("2d")
method applied to the HTML <canvas>
element returns an ImageData object characterised by the pixel data for a
specific rectangle in the canvas.
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.
It has the following
syntax with the following parameters.
context.getImageData(x, y, width, height)
Parameter
|
Required / Optional
|
Description
|
x
|
Required
|
x-coordinate of
upper-left corner
|
y
|
Required
|
y-coordinate of
upper-left corner
|
width
|
Required
|
Width of rectangle, in
pixels
|
height
|
Required
|
Height of rectangle, in
pixels
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span><br><br>
<span id="element2"></span><br><br>
<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");
c2.fillStyle = "rgb(0,0,255)";
c2.fillRect(30, 10, 100, 40);
var imgData = c2.getImageData(30,10,10,10)
var x = document.getElementById("element2")
x.innerHTML = "imgData length = " + imgData.data.length +
"<br>imgData.data[0 to 3] = " + imgData.data[0] + ", " +
imgData.data[1] + ", " + imgData.data[2] + ", " +
imgData.data[3]
document.getElementById("element").appendChild(x2);
</script>
</body>
</html>
|
FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvas2dGetImageData() {
var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.getImageData;
} |
NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)