3

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

     });
gman
  • 100,619
  • 31
  • 269
  • 393
Zsolt Fekete
  • 33
  • 1
  • 6
  • Does your code work? – pokeybit Jul 23 '17 at 09:27
  • yes but the problem is the cursor only changes on the last element of the array i guess its something with the else part. – Zsolt Fekete Jul 23 '17 at 09:31
  • Yes, in this `else` you are setting the cursor to `"default"` when one of the objects is not hovered. So you are actually setting it at least (room1.length - 1) times to default. A correct solution would be to change your `onhover` to return a boolean, check if `room1.some(obj => obj.onhover)` and there set it to `'cursor'` or `'default'`. Ps : avoid doing useless call to DOM in a loop. Store your element in a variable instead (`var canvas = document.getElementById('mainCanvas')`) – Kaiido Jul 23 '17 at 09:41
  • This is the solution i needed, thank you ! – Zsolt Fekete Jul 23 '17 at 09:58

1 Answers1

4

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!

Jeff G
  • 122
  • 1
  • 6