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}
     
     
  • 相关阅读:
    node mysql
    css问题
    mac 命令
    js 严格模式
    js 数组
    sass
    js 面向对象 定义对象
    response.getWriter().write("中文");乱码问题
    读取文件并找出年龄最大的N个人-兰亭集市笔试题
    阿里巴巴暑期实习生笔试
  • 原文地址:https://www.cnblogs.com/crackpotisback/p/5297680.html
Copyright © 2011-2022 走看看