gpt4 book ai didi

javascript - 如何在 Javascript 中更改悬停对象的颜色?

转载 作者:搜寻专家 更新时间:2023-11-01 04:43:32 24 4
gpt4 key购买 nike

<分区>

我是 Javascript/Canvas 的新手,我想创建一个动画,当我在 Canvas 中单击时创建圆圈,然后当我将鼠标悬停在圆圈上时它会改变颜色,当鼠标不在时恢复到原始颜色盘旋在他们身上。我能够在单击时创建绘制圆圈的动画,但无法使悬停颜色起作用。我正在尝试使用 Javascript 完全完成此操作,仅使用 HTML 来创建 Canvas 。任何建议都将不胜感激!

    let dots = [];

/** @type {HTMLCanvasElement} */
let canvas = ( /** @type {HTMLCanvasElement} */ document.getElementById("canvas"));
let context = canvas.getContext('2d');

//some state
let mouseX = -10;
let mouseY = -10;

//remember mouse click position
canvas.onclick = function (event) {
mouseX = event.clientX;
mouseY = event.clientY;

let box = (event.target).getBoundingClientRect();
mouseX -= box.left;
mouseY -= box.top;
};

canvas.onmouseleave = function () {
mouseX = -10;
mouseY = -10;
};

var drawCirc = function (hover) {
//clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);

//determine mouse location when outside
//if inwide canvas, make a dot
if ((mouseX > 0) && (mouseY > 0)) {
dots.push({
"x": mouseX,
"y": mouseY
});
}

//draw circles/dots
dots.forEach(function (d) {
context.fillStyle = "#808080";
context.beginPath();
context.arc(d.x - 3, d.y - 3, 10, 0, 2 * Math.PI);
context.fill();
});
window.requestAnimationFrame(drawCirc);
}
drawCirc();
canvas{
border:1px solid black
}
<canvas id="canvas" width="200" height="200"></canvas>

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