开发者

What are the events on a canvas object I can handle?

What events on the canvas object that I can handle. In particular, I'm looking for a mouse click (or down, or up, etc) ev开发者_StackOverflow中文版ent that will give me the x and y within the canvas.


Here is a little [Demo].

var canvas = document.getElementById("canvas");
canvas.onclick = function(e) {
  // mouse coordinates relative 
  // to the canvas element
  var position = canvas.getBoundingClientRect();
  var click = {
    x: e.clientX - position.left,
    y: e.clientY - position.top
  };
};


You cannot attach DOM events to things other than DOM objects (elements). The canvas is a DOM element, the things you are drawing on it are not. In order to get the specific x y coords of where the user clicked, you must attach the click event to your canvas element, and then compare the x,y coords of the click with the x,y coords of your canvas element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜