在画布中获取鼠标位置 [英] Getting mouse location in canvas

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

问题描述

有一种方法可以将位置鼠标放在< canvas> 标签内吗?我想要相对于< canvas> 的右上角的位置,而不是整个页面。

Is there a way to get the location mouse inside a <canvas> tag? I want the location relative to to the upper right corner of the <canvas>, not the entire page.

推荐答案

最简单的方法是在canvas元素中添加一个onmousemove事件监听器,然后你可以从事件本身获取相对于画布的坐标。

Easiest way is probably to add a onmousemove event listener to the canvas element, and then you can get the coordinates relative to the canvas from the event itself.

如果你只需要支持特定的浏览器,这是很容易实现的,但f.ex. Opera和Firefox。

This is trivial to accomplish if you only need to support specific browsers, but there are differences between f.ex. Opera and Firefox.

这样应该适用于这两个:

Something like this should work for those two:

function mouseMove(e)
{
    var mouseX, mouseY;

    if(e.offsetX) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
    }
    else if(e.layerX) {
        mouseX = e.layerX;
        mouseY = e.layerY;
    }

    /* do something with mouseX/mouseY */
}

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

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