我想在鼠标靠近时交换移动的圆圈的方向,但我正在努力弄清楚如何做。
温柔一点,我是新手。
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>
我有一种感觉,它是结束位。
最佳答案
你不比较动画函数中的鼠标位置,所以它不会在每一帧都完成。此外,您根本不将鼠标位置与圆圈位置进行比较。所以假设“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;
}
关于javascript - 如何在 javascript Canvas 上使用鼠标接近度反转圆圈的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51768295/