HTML5 Canvas鼠标坐标 [英] HTML5 Canvas Mouse coordinates

查看:125
本文介绍了HTML5 Canvas鼠标坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有< canvas> 元素的HTML文件,我试图在点击事件。我正在使用此代码:

I have an HTML file with a <canvas> element and I am trying to get the mouse coordinates in the click event. I am using this code:

secondCanvas.addEventListener('click', function(e) {
    console.log(e.pageX)
}, false);

当我点击左上角时,我进入控制台500~数字,而不是零......我需要做什么才能在画布上获得鼠标的坐标?

When I click on the top left point I get in console 500~ number, not zero... what do I need to do to get the coordinates of the mouse on the canvas?

推荐答案

您应该通过以下方式计算画布鼠标的位置从事件偏移量( e.pageX e.pageY )中减去canvas元素偏移量。

这是一个链接,解释了如何获取元素在dom中的位置,代码应如下所示:

You should calculate the canvas mouse position by substracting the canvas element offset from the event offset (e.pageX and e.pageY).
Here's a link that explains how to get an element position in the dom, and the code should look like :

secondCanvas.addEventListener('click', function(e) {
   var pos = {
       x : e.pageX - canvasOffsetX,
       y : e.pageY - canvasOffsetY
   };
   console.log(pos.x)
}, false);

这篇关于HTML5 Canvas鼠标坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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