zoukankan      html  css  js  c++  java
  • 鼠标在窗口中的坐标转换到 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}
     
     
  • 相关阅读:
    远程控制.scrcpy&其他资料&我的游戏辅助方案
    虚拟机.第三方.droid4x(海马玩)
    私.微信
    私.Modbus测试_ZC03_rtu,ascii,tcp
    Modbus资料
    私.Modbus测试_ZC02_串口方式
    私.Modbus测试_ZC01_TCP方式
    私.01.serialport
    C# Type Basics
    NORFLASH驱动详细说明
  • 原文地址:https://www.cnblogs.com/crackpotisback/p/5297680.html
Copyright © 2011-2022 走看看