Thursday, December 1, 2011

GWT Canvas ImageData requires multiple reads to get value

I am wondering if anyone else has encountered this and if so is it a
bug or simply a misunderstanding on my part of how Canvas's ImageData
works.

I am trying to implement a simple hit detection on my canvas where
each graphic in a list is drawn in a solid colour representing its
index in the list. As I go through the list, I check the Alpha value
at the current mouse coordinates to see if they hit the graphic just
drawn and if so I return that graphic as the one that was selected.

The problem I am getting is that after getting the ImageData from the
Canvas and calling imageData.getAlphaAt(0, 0) I always get 0. After a
bunch of testing I found that if I call it multiple times in a row (at
the same location) I will eventually get the correct value. My code is
like the following:

hitContext.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

List<Symbol> graphics = listener.getSymbolList();
for (int i = graphics.size() - 1; i >= 0; i--)
{
graphics.get(i).draw(hitContext, i);

ImageData imageData = hitContext.getImageData(x, y, 1, 1);

// The coordinates for getAlphaAt are those of the imageData
not the original canvas.
int alpha = imageData.getAlphaAt(0, 0); // first time this
method is run, this always returns 0. afterwards, returns expected
result
alpha = imageData.getAlpha(0, 0); // also returns 0
alpha = imageData.getAlpha(0,0); // returns
correct value


if (0 < imageData.getAlphaAt(0, 0))
{
....
}
}


So is this a bug in GWT or is this call assumed to be asynchronous
(although not stated as such) and if so how should I be handling it?

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To post to this group, send email to google-web-toolkit@googlegroups.com.
To unsubscribe from this group, send email to google-web-toolkit+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.

No comments:

Post a Comment