如何在Javascript中将鼠标悬停时更改对象的颜色?

时间:2019-02-08 06:19:45

标签: javascript canvas

我对Javascript / Canvas还是很陌生,我想创建一个动画,当我在画布中单击时创建一个圆圈,然后当我将鼠标悬停在圆圈上时它会更改颜色,而在没有鼠标时它会恢复为原始颜色。悬停在他们身上。我能够在单击时创建绘制圆圈的动画,但是无法使悬停颜色起作用。我正在尝试完全使用Javascript完成此操作,仅将HTML用于创建画布。任何建议,不胜感激!

    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>

2 个答案:

答案 0 :(得分:-1)

Javascript:

object.addEventListener("mouseover", myScript);

示例:

var e = document.getElementById('elementID')

e.onmouseover = function(){e.style.backgroundColor = "blue"}

答案 1 :(得分:-1)

您可以使用鼠标悬停方法

对于jquery,这是示例

networkErrorMessageTranslationKey

对于javascript

onPressError