Is there a way to use getImageData of an image without the canvas? I am wanting to get to pixel color at the mouse position of an image.
Asked
Active
Viewed 1.2k times
1 Answers
11
No, you can't.
But getting the imageData can be done with an in-memory canvas, that's fast and easy :
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = document.getElementById('someImageId');
context.drawImage(img, 0, 0 );
var theData = context.getImageData(0, 0, img.width, img.height);
You may keep the theData
variable so that you don't have to build it at each click.
Note that this won't work if the image comes from another domain (and thus it won't work if you open your html file using file://
instead of http://
).

Denys Séguret
- 372,613
- 87
- 782
- 758
-
Interesting... what reason do they have to block getting the image data of an image from another domain? – Shmiddty Sep 26 '12 at 15:57
-
3This is to prevent XSS attacks. Read [this](http://en.wikipedia.org/wiki/Cross-site_scripting) and [this](https://developer.mozilla.org/en-US/docs/HTTP_access_control). – Denys Séguret Sep 26 '12 at 15:57
-
But what could possibly happen when trying to retrieve an array of integers? – Shmiddty Sep 26 '12 at 15:59
-
1So... it's not that `getImageData` might be vulnerable, it's that the security in place to prevent illicit XSS is more of a sledgehammer than a scalpel? – Shmiddty Sep 26 '12 at 16:02
-
getImageData add vulnerabilities too. In that case I think they were right to include it. – Denys Séguret Sep 26 '12 at 16:18