Get pixel color from resized canvas, on mouseover

為{幸葍}努か 提交于 2019-12-06 13:14:07

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/29030933/get-pixel-color-from-resized-canvas-on-mouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!