Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

javascript - Canvas images and Click event

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...