鼠标在窗口中的坐标转换到 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}
 
 

转载于:https://www.cnblogs.com/crackpotisback/p/5297680.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值