Obba Crazy
Obba Crazy

Reputation: 11

Javascript, canvas mouseover

function loadMain(){
      background.src = "background.png"
      button.src = "button.png"
    }

function drawMain(){
  ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

  ctx.drawImage(button, 100, 100 , canvas.width/10, canvas.height/10);
}

this method does load perfectly, my question is: if my mouse is over that button image, how can i change to button2.png image? thanks

Upvotes: 1

Views: 74

Answers (1)

sielakos
sielakos

Reputation: 2404

Here I wrote simple example with rectangles how to do it.

const c = document.getElementById("canvas");
const ctx = c.getContext("2d");
const msg = document.getElementById("msg");
const locations = [
    {x: 10, y: 10, width: 40, height: 40, title: "first", color: "red"},
    {x: 50, y: 60, width: 30, height: 30, title: "second", color: "blue"},
    {x: 30, y: 160, width: 60, height: 60, title: "third", color: "green"},
    {x: 20, y: 150, width: 40, height: 40, title: "fourth", color: "#ff40A0"}
];

locations.forEach(({x, y, width, height, color}) => {
    ctx.fillStyle = color;
    ctx.fillRect(x, y, width, height);
});

c.addEventListener('mousemove', (event) => {
    const {layerX, layerY} = event;

    const titles = locations
    .filter(({x, y, width, height}) => {
      return layerX >= x && layerX <= x + width 
        && layerY >= y && layerY <= y + height;
    })
    .map(({title}) => title);

    msg.innerHTML = `x: ${layerX}, y: ${layerY},
      titles: ${titles.join(', ')}`;
});

working fiddle: https://jsfiddle.net/mmzr6tgo/

Basic idea is to add new event listener on 'mousemove' event in canvas element and then use layerX and layerY as mouse position in canvas. Then you only have to check if mouse is inside rectangular area, which is simple condition.

Upvotes: 1

Related Questions