开发者

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

开发者 https://www.devze.com 2023-01-25 22:29 出处:网络
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.H

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

精彩评论

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