Javascript,画布鼠标悬停

时间:2016-05-20 05:10:01

标签: javascript canvas

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

此方法确实加载完美, 我的问题是: 如果我的鼠标位于该按钮图像上,我该如何更改为button2.png图像? 感谢

1 个答案:

答案 0 :(得分:1)

在这里,我用矩形编写了一个简单的例子,如何做到这一点。

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(', ')}`;
});

工作小提琴:https://jsfiddle.net/mmzr6tgo/

基本思想是在canvas元素中的'mousemove'事件上添加新的事件侦听器,然后使用layerX和layerY作为画布中的鼠标位置。然后你只需要检查鼠标是否在矩形区域内,这是一个简单的条件。