1 This test ensures that getImageData works correctly.
5 testRunner
.dumpAsText();
7 var canvas
= document
.createElement("canvas");
10 var context
= canvas
.getContext("2d");
13 document
.getElementById("log").innerHTML
+= msg
+ "<br/>";
16 function dataToArray(data
) {
17 var result
= new Array(data
.length
)
18 for (var i
= 0; i
< data
.length
; i
++)
23 function getPixel(ctx
, x
, y
) {
24 var data
= ctx
.getImageData(x
,y
,1,1);
25 if (!data
) // getImageData failed, which should never happen
27 return dataToArray(data
.data
);
30 function pixelShouldBe(ctx
, x
, y
, colour
) {
31 var ctxColour
= getPixel(ctx
, x
, y
);
33 for (var i
= 0; i
< 4; i
++)
34 if (colour
[i
] != ctxColour
[i
]) {
39 log("PASS: pixel at ("+[x
,y
]+") was ["+colour
+"]");
41 log("FAIL: pixel at ("+[x
,y
]+") was ["+ctxColour
+"], expected ["+colour
+"]");
44 if (!context
.setFillColor
)
45 context
.setFillColor = function(r
,g
,b
,a
) {
46 this.fillStyle
= "rgba("+[Math
.round(r
*255),Math
.round(g
*255),Math
.round(b
*255),Math
.round(a
*255)]+")"
49 // Check that getImageData is return the data for the right portion of the image
50 for(var x
= 0; x
< 100; x
+=4) {
51 context
.setFillColor(0, x
/96, 0, 1);
52 context
.fillRect(x
,0,1,1);
53 pixelShouldBe(context
, x
, 0, [0, Math
.round(255*x
/96), 0, 255]);
56 // Check rgba ordering
57 context
.clearRect(0,0,100,100);
58 context
.setFillColor(0.25, 0.5, 0.75, 1);
59 context
.fillRect(5,5,1,1);
60 pixelShouldBe(context
, 5, 5, [Math
.round(0.25*255), Math
.round(0.5*255), Math
.round(0.75*255), 255]);
62 // Make sure we return correct values for the row
63 for (var i
= 0; i
< 100; i
++) {
64 context
.fillStyle
= "rgba("+[0, i
, 0, 1]+")";
65 context
.fillRect(i
, 10, 1, 1);
68 var rowImageData
= context
.getImageData(0, 10, 100, 1).data
;
70 for (var i
= 0; i
< 100; i
++) {
71 if (rowImageData
[i
* 4 + 1] != i
) {
77 log("FAIL: Did not correctly retrieve every pixel in a row");
79 log("PASS: Correctly retrieved every pixel in a row");
81 // Check that we return transparent black for regions outside the canvas proper
82 context
.fillStyle
= "rgba(255,255,255,255)";
83 context
.fillRect(198, 5, 4, 1); // final 2 pixels horizontally should be clipped
84 var content
= dataToArray(context
.getImageData(198, 5, 4, 1).data
);
85 var expected
= [255,255,255,255,255,255,255,255,
88 for (var i
= 0; i
< 16; i
++)
89 if (content
[i
] != expected
[i
]) {
94 log("PASS: Correct data for content outside canvas bounds");
96 log("FAIL: Did not get correct data for content outside canvas bounds: "+content
);