HTML5 Multiple Canvases事件监听器 - 如何确定哪个画布经历了事件? [英] HTML5 Multiple Canvases event listener - how to determine which canvas experienced the event?

查看:272
本文介绍了HTML5 Multiple Canvases事件监听器 - 如何确定哪个画布经历了事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS的新手。我没有使用jQuery,我有一个问题。我在页面上创建了一个可变数量的画布,都有一个像这样的eventlistener:

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); }

给定监听器功能clickReporter:

Given the listener function clickReporter:

        function clickReporter(e){...}

I我试图使用这个函数来告诉我相对于画布的click事件的鼠标位置:

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
};

}

我从这里找到教程: http://www.html5canvastutorials.com/advanced/html5-canvas- mouse-coordinates /

问题是,它假设只有一个画布,而且我现在有一个画布列表放在一个画布上网页,但我想知道,只要clickReporter()函数,有一个简单的方法来确定选择哪个画布?像evt.getCanvas()或evt.getParentCanvas()这样的函数?

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)

推荐答案

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
}

这篇关于HTML5 Multiple Canvases事件监听器 - 如何确定哪个画布经历了事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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