Search code examples
javascripthtmlcanvasdrawing

check if a element is being hovered on in javascript


I have a canvas picture made in javascript and i want to check if the mouse cursor is hovering over the canvas. this is how my code looks like

window.onload = function() {     
     var Gamecanvas = document.getElementById('game');
     var GameCTX = Gamecanvas.getContext('2d');
     function soapDraw() {
         var soap = new Image();
         soap.src = 'Soap.png';         
         soap.onload = function() {
              GameCTX.drawImage(soap, 5, 5);
         };
     };
     soapDraw(); 
}

this code loads a image of soap and i want to if the cursor hovers over the soap, it moves, though i am not onto the moving part yet...

I do not want any jquery answers. I want javascript non-query answers

I tried jquery answers on other forums but i have no experience with jquery and i dont know how to adjust it to my needs.

Edit: this is how my site looks like: this website picture


Solution

  • you can use an event listener directly on canvas and watching for mouseover event

    Gamecanvas.addEventListener('mouseover', (event) => { /* your code goes here */});
    

    for a more complete answer look here