最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Handling OnClick event for canvas in javascript and getting its coordinates - Stack Overflow

programmeradmin3浏览0评论

I have a canvas for drawing like that

<div id="canvas" style="position:relative;width:600px;height:300px;" onclick="q()"></div>

I need to handle the event when clicking on it and get the coordinates on the canvas where it was clicked

I have a canvas for drawing like that

<div id="canvas" style="position:relative;width:600px;height:300px;" onclick="q()"></div>

I need to handle the event when clicking on it and get the coordinates on the canvas where it was clicked

Share Improve this question asked Jun 10, 2011 at 0:32 Ahmad FaridAhmad Farid 14.8k45 gold badges98 silver badges138 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

You need to get the page x and y coordinates, and then minus the canvas offset to get them relative to the canvas.

function q(event) {
    event = event || window.event;

    var canvas = document.getElementById('canvas'),
        x = event.pageX - canvas.offsetLeft,
        y = event.pageY - canvas.offsetTop;

    alert(x + ' ' + y);
}

jsFiddle.

You should consider attaching events unobtrusively, i.e. not using the onclick HTML attribute.

Using jQuery, you can just read the .pageX and .pageY attributes directly.

http://docs.jquery.com/Tutorials:Mouse_Position#Where_did_they_click_that_div.3F

Since HTML5, just get the layerX and layerY attributes of the event itself. Nice!

发布评论

评论列表(0)

  1. 暂无评论