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.
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).
// 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;
In addition the code need to have some boundary check of the coordinates so getImageData()
won't fail (not shown here).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.