javascript - 如何在 javascript 画布上通过鼠标接近来反转圆圈的方向?
问题描述
当鼠标靠近时,我想交换圆圈移动的方向,但我很难弄清楚如何。
温柔点,我是新手。
- 这
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;
}
推荐阅读
- sql - Microsoft Access 相当于 OPENQUERY()
- java - 我正在做一个项目,它不断地给我以前配对的设备的 RSSI。我没有得到连续的结果
- android - 如何制作警报对话框项目?
- ios - 应用旋转变换后如何获得 UIImageView 的实际角点
- vue.js - Vuex 使用 watcher 登录
- google-cloud-platform - 有没有办法通过 gcloud SDK 了解 GCP 实例的创建者?
- c# - 命名空间名称和模型冲突
- asp.net-core - Microsoft.AspNetCore.All 2.1.4 是否支持 DotNetCore 2.2?
- javascript - 如何使用 node.js 读取和解析来自 TCP 连接的原始数据
- powerbi - 如何连接 MySQL 查询与 Power BI 组件