在鼠标悬停时从调整大小的画布中获取像素颜色 [英] Get pixel color from resized canvas, on mouseover

查看:175
本文介绍了在鼠标悬停时从调整大小的画布中获取像素颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已检查过此问题,它提供了完美的答案。但我的问题略有不同。我有一张帆布 300 x 300 ,我使用 css 重新调整画布大小到 200 x 60 。如果我重新调整大小的画布使用CSS我不能得到颜色值 onmouseover

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.

你会注意到它仍然表示#FF0000 & #0000FF ,而应该是#000000 。那么如何在重新调整大小的画布时也能正常工作?

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?

小提示:用css重新调整大小。

Fiddle: Re-sized with css.

小提琴:不重新调整大小。

推荐答案

您需要在鼠标处理程序方法中应用缩放因子。比例因子是您的画布的位图(实际大小)和元素大小(CSS大小)之间的关系。

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;

更新小提琴

Updated fiddle

此外,代码需要对坐标进行一些边界检查, $ c> getImageData()不会失败(此处未显示)。

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

这篇关于在鼠标悬停时从调整大小的画布中获取像素颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆