由于需要用到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}
原文:http://www.cnblogs.com/crackpotisback/p/5297680.html