首页 > 解决方案 > 如何在 javascript 画布上通过鼠标接近来反转圆圈的方向?

问题描述

当鼠标靠近时,我想交换圆圈移动的方向,但我很难弄清楚如何。

温柔点,我是新手。

代码

var canvas = document.querySelector('canvas');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var conte = canvas.getContext('2d');

var l = 200;
var dl = 7;
var radius = 30;

var mouse = {
    x: undefined,
    y: undefined
}

window.addEventListener('mousemove', 

    function(event) {
        mouse.x = event.x;
        mouse.y = event.y;
        console.log(mouse);
    })

    function animate() {
       requestAnimationFrame(animate);

       conte.fillStyle = 'rgba(255, 255, 255, 0.05)';
       conte.fillRect(0, 0, canvas.width, canvas.height);

       conte.beginPath();

       conte.arc(l, 200, radius, 0, Math.PI * 2, false);
       conte.strokeStyle = '#E3DACD';
       conte.stroke();
       conte.fillStyle = '#B8B0A6';
       conte.fill();

       if (l + radius > innerWidth || l - radius < 0) {
           dl = -dl;
       }

       l += dl;

       conte.fillStyle = 'rgba(255, 255, 255, 0.05)';
       conte.fillRect(0, 0, canvas.width, canvas.height);

       conte.beginPath();

       conte.arc(l, 300, radius, 0, Math.PI * 2, false);
       conte.strokeStyle = '#B0B1A1';
       conte.stroke();
       conte.fillStyle = '#98998B';
       conte.fill();

       conte.fillStyle = 'rgba(255, 255, 255, 0.05)';
       conte.fillRect(0, 0, canvas.width, canvas.height);

       conte.beginPath();

       conte.arc(l, 400, radius, 0, Math.PI * 2, false);
       conte.strokeStyle = '#6C7974';
       conte.stroke();
       conte.fillStyle = '#545E5A';
       conte.fill();

       conte.fillStyle = 'rgba(255, 255, 255, 0.05)';
       conte.fillRect(0, 0, canvas.width, canvas.height);

       conte.beginPath();

       conte.arc(l, 500, radius, 0, Math.PI * 2, false);
       conte.strokeStyle = '#935F39';
       conte.stroke();
       conte.fillStyle = '#7D5130';
       conte.fill();

       conte.fillStyle = 'rgba(255, 255, 255, 0.05)';
       conte.fillRect(0, 0, canvas.width, canvas.height);

       conte.beginPath();

       conte.arc(l, 100, radius, 0, Math.PI * 2, false);
       conte.strokeStyle = '#E7B99F';
       conte.stroke();
       conte.fillStyle = '#CFA58E';
       conte.fill();

   };

if (mouse.x > radius +10 || mouse.x < radius) {


    if (l + radius > innerWidth || l - radius < 0) {
        dl = -dl;
    }

    l -= dl;

};


animate();
<canvas id="canvas">
</canvas>

我有一种感觉,它的结束位。

标签: javascripthtml5-canvas

解决方案


您不会比较动画功能内的鼠标位置,因此不会每帧都进行。此外,您根本不会将鼠标位置与圆圈位置进行比较。所以假设“l”是圆的水平位置,垂直位置是200,半径是30:

if(mouse.y < 230 && mouse.y > 170 && mouse.x < l + 30 && mouse.x > l - 30) {
    //the mouse touches the circle
    dl = -dl;
}

推荐阅读