鼠标在没有库的画布中的位置? [英] Mouse position in canvas without a library?

查看:57
本文介绍了鼠标在没有库的画布中的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找如何获得相对于画布的鼠标位置,但是没有JS库...除了jquery之外,找不到其他示例!

I been searching around to find how to get the mouse position relative to canvas but without a JS library...can't see to find any examples except for jquery!

我用它来启动我的功能:

I use this to start my function:

 canvas = document.getElementById("canvas");  
 ctx = canvas.getContext("2d"); 
 canvas.addEventListener("mousedown", mousePos, false);

但是e.pageX和e.pageY受画布位置的影响。我需要删除该问题,以便数学是正确的,因此仅基于画布。

But e.pageX and e.pageY is affected by the position of the canvas. I need to remove that issue so the maths is correct so its only based on the canvas.

可以在没有JS库的情况下完成此操作吗?如我所见,jquery尽量避免使用它。

Can this be done without a JS library? As I have only ever seen it done with jquery which i'm trying to avoid as much as possible.

推荐答案

var findPos = function(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) { 
        do {
           curleft += obj.offsetLeft;
           curtop += obj.offsetTop; 
        } while (obj = obj.offsetParent);
    }
    return { x : curleft, y : curtop };
};

获取canvas元素的位置并从中减去x和y。

Get the position of the canvas element and subtract the x and y from it.

这篇关于鼠标在没有库的画布中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆