将鼠标悬停在画布上的图像上

时间:2022-04-07 07:46:33

I am trying to make a simple point and click game with canvas and i'd like to change the cursor to pointer when i hover on a drawn image and change it back to default when i hover off. So i was trying to make an onhover function for each object on my canvas. Is there any easy way to check if i hover over an image ? My code looks something like this so far :

我正在尝试使用画布制作一个简单的点和点击游戏,当我将鼠标悬停在绘制的图像上时,我想将光标更改为指针,当我将鼠标悬停时将其更改为默认值。所以我试图为我画布上的每个对象创建一个onhover函数。有没有简单的方法来检查我是否将鼠标悬停在图像上?到目前为止,我的代码看起来像这样:

//heres an object for my canvas
var cupboard = {
x:200,
y:320,
h:300,
w:180,
imgUrl:"data\\cbc.png",
type:2,
status:'c',
onhover: function(e,canvas)
{
    if((e.x >= this.x && e.x <= this.x+this.w) &&(e.y >= this.y && e.y <= 
    this.y+this.h)){
        canvas.style.cursor = "pointer";
    }
    else
    {
        canvas.style.cursor = "default";
    }
}
//i use an array for these objects
room1[cupboard,silverkey];

//heres the event listener   
 document.getElementById("mainCanvas").addEventListener("mousemove",
function(evt){
         var mousepos = getMousePos(document.getElementById("mainCanvas"),evt);
         for(i in room1)
         {
             (function(m){
                 room1[m].onhover(mousepos,document.getElementById("mainCanvas"));
             })(i);
         }

     });

1 个解决方案

#1


1  

I had a look online for a solution and cam across this page :

我在网上看了一个解决方案,并在这个页面上显示:

Add onclick and onmouseover to canvas element

将onclick和onmouseover添加到canvas元素

markE's answer is very long but could be useful for you, especially the part about '.isPointInside'.

markE的答案很长,但对你有用,特别是关于'.isPointInside'的部分。

Hope this helps!

希望这可以帮助!

#1


1  

I had a look online for a solution and cam across this page :

我在网上看了一个解决方案,并在这个页面上显示:

Add onclick and onmouseover to canvas element

将onclick和onmouseover添加到canvas元素

markE's answer is very long but could be useful for you, especially the part about '.isPointInside'.

markE的答案很长,但对你有用,特别是关于'.isPointInside'的部分。

Hope this helps!

希望这可以帮助!