画布图片和点击事件 [英] Canvas images and Click event

查看:362
本文介绍了画布图片和点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在< canvas> 标签中有两个圆圈,包含HTML5&

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)如何处理使用< canvas>

2)如何清除/删除 ; canvas>

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

推荐答案

技术上没有办法在画布形状上注册鼠标事件。然而,如果你使用一个库,如Raphael(http://raphaeljs.com/),它可以跟踪形状位置,从而弄清楚什么形状接收鼠标事件。这里有一个例子:

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

这篇关于画布图片和点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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