gpt4 book ai didi

JavaScript, Canvas 鼠标悬停

转载 作者:行者123 更新时间:2023-11-27 22:58:42 25 4
gpt4 key购买 nike

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图像?谢谢

最佳答案

这里我用矩形编写了简单的示例,说明如何做到这一点。

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

工作 fiddle :https://jsfiddle.net/mmzr6tgo/

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

关于JavaScript, Canvas 鼠标悬停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37338347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com