'onmouseover'画布中的元素?

时间:2016-07-11 16:56:58

标签: javascript css hover onmouseover

我正在制作一个HTML / JS / CSS游戏,并且已经停止了!我不确定如何在画布中使用带有元素的'onmouseover'标签。请帮助!

尝试:

particle.onmouseover=function(){myScript};

这是我到目前为止所拥有的:

for (var i = 0; i < 100; i++) { //add particles with random postions
  particles.push(new creat_particle());
}
//function for multiple particles 
function creat_particle() {
  this.x = Math.random() * W;
  this.y = Math.random() * H;
  //Random Color 
  var r = Math.random() * 255 >> 0;
  var g = Math.random() * 255 >> 0;
  var b = Math.random() * 255 >> 0;
  this.color = "rgba(" + r + "," + g + "," + b + ",0.5)";
  //random size 
  this.radius = Math.random() * 45 + 5;
}

任何帮助表示赞赏...

1 个答案:

答案 0 :(得分:0)

您需要做的是为画布添加鼠标悬停事件,获取鼠标位置,然后将其与粒子位置进行比较,如下所示。

canvas.onmouseover = function(event) {

    for(i=0;i<100;i++) {
// assuming canvas is positioned at 0,0 of the page
      if(event.clientX => particle[i].x - particle[i].radius&& event.clientX <= particle[i].x + particle[i].radius && event.clientY => particle[i].y - particle[i].radius&& event.clientY <= particle[i].y + particle[i].radius) {
// your event handler code here
      }
     }
   };

由于粒子呈圆形,因此会有轻微的不准确性。