Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have currently two circles in a <canvas> tag with HTML5 & JavaScript.

Now I'm trying to add an image (done) that changes based on mouse-over and click.

It's basically an implementation of a play / pause button with an extra color change when the user mouse-overs the button.

I can't seem to figure out how events work on shapes in HTML5 since they are not objects ... Here is my code at the moment :

window.onload = function() {

      var canvas = document.getElementsByTagName('canvas')[0];
      var context = canvas.getContext('2d');
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;


      //Outer circle
      context.beginPath();  
      context.arc(centerX, centerY, 150, 0, Math.PI * 2, false);
      context.fillStyle = "#000";
      context.fill();
      context.stroke();

      //Inner cicle
      context.beginPath();
      context.arc(centerX, centerY, 75, 0, Math.PI * 2, false);
      context.fillStyle = "#fff";
      context.fill();
      context.stroke();

      //Play / Pause button
      var imagePlay = new Image();
      var imageHeight = 48/2;
      imagePlay.onload = function() {
        context.drawImage(imagePlay, centerX - imageHeight, centerY - imageHeight);
      };
      imagePlay.src = "images/play.gif";

}
  1. How to handle events on shapes created with <canvas>?

  2. How to clean-up / remove images on the <canvas> when replacing it with another one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
623 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is technically no way to register mouse events on canvas-drawn shapes. However, if you use a library, like Raphael (http://raphaeljs.com/), it can keep track of shape positions and thus figure out what shape is receiving the mouse event. here's an example:

var circle = r.circle(50, 50, 40);

circle.attr({fill: "red"});

circle.mouseover(function (event) {
    this.attr({fill: "red"});
});

As you can see, it's very simple this way. For modifying shapes, this library will also come in handy. Without it you would need to remember how to redraw everything each time you make a change


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...