Oliver Scholl
Oliver Scholl

Reputation: 63

Get color of a point on the canvas

Is it possible to get the color (rgb-value and transparency) of a point (x/y-coordinate) from the canvas? Example: I draw some figures and text on a canvas and later I want to get the color of a point at a specific coordinate.

The solution should be independent whether the canvas is visible on screen or not. And it should work independently from the operating system.

I didn't found any solution on the web. That's why I assume that this is not possible. Am I right?

Upvotes: 0

Views: 419

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137707

The canvas isn't very pixel-based, and provides no API for doing this.

But if you've got the tkimg package installed, you can use that to do a screengrab of the canvas and then fetch the pixel value out of that.

package require Img

# Get the data into an image
set screengrab [image create photo -format window -data $theCanvas]
# Read the pixel data out of the grabbed image
set pixeldata [$screengrab get $x $y]
# Get rid of the grabbed data once you're done
image delete $screengrab

Note that the coordinates concerned will be viewport coordinates, not canvas internal coordinates: if you've scrolled the canvas, you'll have to offset as necessary.

Upvotes: 2

Bryan Oakley
Bryan Oakley

Reputation: 386220

You are correct, tk does not provide any way to get the color of a specific pixel on a canvas.

Upvotes: 1

Related Questions