Get pixel color from resized canvas, on mouseover
Asked Answered
V

1

1

I have checked this question which provides the perfect answer. But my problem is slightly different. I have a canvas of 300 x 300 and i am re-sizing the canvas using css to 200 x 60. If i re-size the canvas using css i am not able to get the color value onmouseover.

In the re-sized fiddle if you mouse over right below the red or blue rectangles you will notice it still says #FF0000 & #0000FF respectively while it should be #000000. So how to make it work even with re-sized canvas?

Fiddle: Re-sized with css.

Fiddle: Non re-sized.

Velure answered 13/3, 2015 at 11:22 Comment(0)
G
4

You need to apply a scale factor inside the mouse handler method. The scale factor is the relationship between your canvas's bitmap (actual size) and the element size (CSS size).

For example:

// find scale:
var sx = example.width / parseInt(example.style.width, 10);
var sy = example.height / parseInt(example.style.height, 10);

// apply to x/y
x = (x * sx)|0;  // scale and cut any fraction to get integer value
y = (y * sy)|0;

Updated fiddle

In addition the code need to have some boundary check of the coordinates so getImageData() won't fail (not shown here).

Gambia answered 13/3, 2015 at 12:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.