将Click事件处理程序添加到多个画布上

时间:2014-07-31 15:12:27

标签: javascript html5-canvas

我是javascript和HTML5的新手,所以请原谅我是一个愚蠢的错误

我用一些文本和一个矩形以编程方式绘制3个画布,我想在每个上面点击事件,我还需要知道哪个画布已被点击,我写了下面的代码,但doMouseDown函数执行即使没有点击

<canvas id="myCanvas1" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<canvas id="myCanvas2" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>
<canvas id="myCanvas3" width="452" height="80" style="border:0px solid #d3d3d3;"></canvas>

       <script>
        function init()
        {
            var rect = { w: 300, h: 60 };
            var point = { x: 150, y: 10 };

            for (var i = 1 ; i < 4 ; i++) {
                var canvasStr = "myCanvas" + Number(i);
                var c = document.getElementById(canvasStr);
                var context = c.getContext("2d");

                // text
                context.font = "22pt Arial";
                context.lineWidth = 2;
                context.fillStyle = "#000000";

                var studentStr = "Student " + Number(i);
                context.fillText(studentStr, 5, 50);

                // rectangle
                context.strokeStyle = "black";
                context.strokeRect(point.x, point.y, rect.w, rect.h);

                context.fillStyle = "#00FF00";
                context.fillRect(point.x, point.y, rect.w, rect.h);
                c.addEventListener('mousedown', doMouseDown(canvasStr), false);
            }
        }

        function doMouseDown(canvasStr)
        {
            alert(canvasStr);
        }

        init();
    </script>

如何修复它并知道哪个画布已被点击(在本例中为canvasStr)

3 个答案:

答案 0 :(得分:1)

你可以这样做

c.addEventListener("mousedown", function () {
                    doMouseDown(canvasStr)
                }, false);

然后写入该函数

 function doMouseDown(canvasStr) {
             alert(canvasStr);
          }

答案 1 :(得分:1)

如果您在循环中附加侦听器,则必须创建一个闭包,否则canvasStr总是== myCanvas3

(function(str) {
    c.addEventListener('mousedown', doMouseDown.bind(str), false);
}(canvasStr));

然后你的回调应该是:

function doMouseDown(e, canvasStr) {
    alert(canvasStr);
} 

第一个参数eEvent对象,它总是被传递给回调。

<强> ADDED 这样做没有意义:

var canvasStr = "myCanvas" + Number(i);

i已经是一个数字,您将其添加到字符串中。只需写下:

var canvasStr = "myCanvas" + i;

答案 2 :(得分:1)

另一种方法是将所有3个画布包装在容器div中并侦听容器上的事件

http://jsfiddle.net/m1erickson/g7fsS/

<div id="container">
    <canvas id="myCanvas1" width="45" height="80"></canvas>
    <canvas id="myCanvas2" width="45" height="80"></canvas>
    <canvas id="myCanvas3" width="45" height="80"></canvas>
</div>           


document.getElementById("container").addEventListener("click",function(e){
    console.log(e.target.id);
},false);