鼠标在窗口中的坐标转换到 canvas 中的坐标

 
 

鼠标在窗口中的坐标转换到 canvas 中的坐标

由于需要用到isPointInPath函数,所以必须得将鼠标在窗口中的坐标位置转换到canvas画布中的坐标,今天发现网上这种非常常见的写法其实是错误的!

代码如下:

1.function windowTocanvas(canvas, x, y) {
2. var bbox = canvas.getBoundingClientRect();
3. return {
4. x: x - bbox.left * (canvas.width / bbox.width),
5. y: y - bbox.top * (canvas.height / bbox.height)
6. };
7.}

什么时候会发生错误呢?
看下面的LiveScript代码

1.canvas = document.querySelector \canvas
2.ctx = canvas.getContext \2d
3.dpr = window.devicePixelRatio || 1
4.width = parseInt canvas.style.width
5.height = parseInt canvas.style.height
6.canvas.width = width * dpr
7.canvas.height = height * dpr
8.ctx.scale dpr, dpr

当用到window.devicePixelRatio的时候,会出现鼠标命明明击中了path,却出现isPointInPath却报false的情况。

真正的window2canvas写法应该如下:

1.window2canvas = (e) ->
2. rect = canvas.getBoundingClientRect!
3. x = (e.clientX - rect.left) * canvas.width / rect.width
4. y = (e.clientY - rect.top ) * canvas.height / rect.height
5. {x, y}
 
 
posted @ 2016-03-20 14:13  狂徒归来  阅读(621)  评论(0编辑  收藏  举报