问题
I'm new to JS. I'm not using jQuery, and I have a question. I've created a variable number of canvases on a page, all have an eventlistener like so:
for (i=0; i<numberOfCanvases; i++){
var canv = document.createElement("canvas");
canv.addEventListener('click', clickReporter, false);
document.body.appendChild(canv); }
Given the listener function clickReporter:
function clickReporter(e){...}
I am trying to use this function to tell me the mouse position of the click event relative to the canvas:
function getMousePos(canvas, evt){
// get canvas position
var obj = canvas;
var top = 0;
var left = 0;
while (obj && obj.tagName != 'BODY') {
top += obj.offsetTop;
left += obj.offsetLeft;
obj = obj.offsetParent;
}
// return relative mouse position
var mouseX = evt.clientX - left + window.pageXOffset;
var mouseY = evt.clientY - top + window.pageYOffset;
return {
x: mouseX,
y: mouseY
};
}
which i found from this tutorial: http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
The problem is, it assumes there is only one canvas, and I do have a list of canvases right now that are placed on a webpage, but I was wondering, given just the clickReporter() function, is there an easy way to determine which canvas was selected? a function like evt.getCanvas() or evt.getParentCanvas()?
I'm asking because when an event occurs (a mouse click on 1 of many canvases, I want to create actions at that location for ONLY that canvas)
回答1:
function clickReporter(e){
console.log( this ); // in a eventListener , this point to the element fire the event
console.log( e.target ); // in fireFox and webkit, e.target point to the element fire the event
}
回答2:
I would think evt.target (event.target) would work.
来源:https://stackoverflow.com/questions/10508357/html5-multiple-canvases-event-listener-how-to-determine-which-canvas-experienc