我的EventListener无法正常工作

时间:2013-02-14 14:53:31

标签: javascript html html5 canvas html5-canvas

我想要做的是,如果我将鼠标悬停在我绘制的一个物体上,我想要显示一个模糊信息,说明它是哪个城市,人口和市中心的图像等等,现在我只是试着让它运转起来。我也想知道是否还有其他东西我可以而不是提醒,这会产生泡沫

<script>
    function startCanvas() {
      var c = document.getElementById("myCanvas");
      var ctx = c.getContext("2d");
      //first circle
      var one = c.getContext("2d");
      //second circle
      var two = c.getContext("2d");
      //third cirle
      var three = c.getContext("2d");
      //fourth circle
      var four = c.getContext("2d");
      //fifth cirle
      var five = c.getContext("2d");
      // new image
      var image = new Image();
      image.onload = function () {
        ctx.drawImage(image, 69, 50);
        //draw a circle
        one.beginPath();
        one.arc(180, 90, 10, 0, Math.PI * 2, true);
        one.closePath();
        one.fill();
        two.beginPath();
        two.arc(155, 138, 10, 0, Math.PI * 2, true);
        two.closePath();
        two.fill();
        three.beginPath();
        three.arc(160, 180, 10, 0, Math.PI * 2, true);
        three.closePath();
        three.fill();
        four.beginPath();
        four.arc(257, 210, 10, 0, Math.PI * 2, true);
        four.closePath();
        four.fill();
        five.beginPath();
        five.arc(238, 235, 10, 0, Math.PI * 2, true);
        five.closePath();
        five.fill();
      };
      image.src = 'denmark.jpg';



    //function hover over circle one, give alert
      one.addEventListener('mouseover',  
       function (e) {
           e = e || window.event;
           alert('this is a test');
       }
       );


    }
    </script>
    </head>
    <body onload="startCanvas()">
      <canvas id="myCanvas" width="600" height="600";">
        Your browser does not support the HTML5 canvas tag.
      </canvas>
    </body>
    </html>

2 个答案:

答案 0 :(得分:0)

您是否考虑使用稍高级别的绘图库,例如RaphaelJS?或EaselJS

我已经搞砸了这两种方式,它们使这种交互式画布更加优雅,并且还可以提高您的跨浏览器兼容性。

答案 1 :(得分:0)

您的代码会抛出此错误

  • 对象#&lt; CanvasRenderingContext2D&gt;没有方法'addEventListener'

所以修改这个部分

  //function hover over circle one, give alert
  one.addEventListener('mouseover',  
   function (e) {
       e = e || window.event;
       alert('this is a test');
   }
   );

通过此代码

//function hover over circle one, give alert
  c.addEventListener('mouseover',  
   function (e) {
       e = e || window.event;
       alert('this is a test');
   }
   ,false);

这将起作用;