Zsolt Fekete
Zsolt Fekete

Reputation: 33

Hover on images in a canvas

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 :

//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);
         }

     });

Upvotes: 3

Views: 4313

Answers (1)

Jeff G
Jeff G

Reputation: 122

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

Add onclick and onmouseover to canvas element

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

Hope this helps!

Upvotes: 4

Related Questions