[英]Get pixel color from resized canvas, on mouseover
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
. 我有一个300 x 300
的画布,我正在使用css
将画布调整为200 x 60
。 If i re-size the canvas using css i am not able to get the color value onmouseover
. 如果我使用CSS重新调整画布的大小,则无法在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
. 在调整大小的小提琴中,如果将鼠标悬停在红色或蓝色矩形的正下方,您会注意到它仍然分别显示#FF0000
和#0000FF
而它应该是#000000
。 So how to make it work even with re-sized canvas? 那么,如何使它即使在调整尺寸的画布上也能正常工作?
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). 比例因子是画布的位图(实际大小)与元素大小(CSS大小)之间的关系。
// 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). 另外,代码需要对坐标进行一些边界检查,以使getImageData()
不会失败(此处未显示)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.