Geuis
Geuis

Reputation: 42297

Javascript - get pixel data from image under canvas element?

You can sample pixel color data on a canvas image with getImageData(). If I layer a transparent canvas element over a background image or flash movie, can I sample a color from that via the canvas tag?

Upvotes: 3

Views: 8597

Answers (2)

bobince
bobince

Reputation: 536765

Phil's right, you can't do it. Canvas, by design, only returns its own intrinsic pixel data, not any on-screen rendered content originating from other elements.

You could make a canvas element that covers the entire page and captures an image of the rendered screen.

If possible, that would be a cross-site-scripting security hole. You could iframe a target site (leveraging the users cookies/authentication/intranet to access it), then suck out the content from it pixel by pixel.

Upvotes: 5

Phil H
Phil H

Reputation: 20151

I think not. You would get the colour of the canvas at that point. I did find the method document.defaultview.getComputedStyle(element,pseudoElt), but on a 1 pixel div with no background-color, it returned 'transparent'.

So, unfortunately, this may be impossible at present. What is your higher-level aim? We may be able to come up with an alternative route.

"I had an idea earlier to copy image data into a javascript object. You could make a canvas element that covers the entire page and captures an image of the rendered screen. Once you have that data, you could do real-world cross browser testing, perhaps."

If you don't mind that it's a static image, there is a great website that does this for you: Browser Shots. It generates screenshots of your website running in a huge range of different browsers.

Upvotes: 2

Related Questions