如何在JavaScript画布上通过鼠标接近来反转我的圈子的方向?

时间:2018-08-09 13:25:46

标签: javascript html5-canvas

我想交换鼠标靠近时圆圈的移动方向,但我一直在努力寻找方法。

要温柔,我是新来的。

  • conte只是上下文,我的说法是c.something

代码

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>

我觉得这是结束。

1 个答案:

答案 0 :(得分:2)

您不比较动画功能中的鼠标位置,因此不会每帧完成一次。同样,您根本不将鼠标位置与圆圈位置进行比较。因此,假设“ 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;
}