欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > JavaScript + HTML5 Canvas 实现互动爱心雨

JavaScript + HTML5 Canvas 实现互动爱心雨

2025/2/21 3:01:39 来源:https://blog.csdn.net/hl826669/article/details/145635972  浏览:    关键词:JavaScript + HTML5 Canvas 实现互动爱心雨
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>情人节快乐!</title><style>body {margin: 0;overflow: hidden;}canvas {display: block;}</style>
</head><body><canvas id="canvas"></canvas><script>const canvas = document.getElementById('canvas');const ctx = canvas.getContext('2d');canvas.width = window.innerWidth;canvas.height = window.innerHeight;// 爱心类class Heart {constructor() {this.x = Math.random() * canvas.width;this.y = Math.random() * -canvas.height;this.size = Math.random() * 10 + 10;this.speed = Math.random() * 2 + 1;}draw() {ctx.beginPath();const t = Date.now() / 1000;const x = 16 * Math.pow(Math.sin(t), 3);const y = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t);const scaledX = this.x + x * this.size;const scaledY = this.y - y * this.size;ctx.moveTo(scaledX, scaledY);ctx.bezierCurveTo(scaledX + this.size, scaledY - this.size, scaledX + 2 * this.size, scaledY + this.size, scaledX, scaledY + 2 * this.size);ctx.bezierCurveTo(scaledX - 2 * this.size, scaledY + this.size, scaledX - this.size, scaledY - this.size, scaledX, scaledY);ctx.fillStyle = 'red';ctx.fill();}move() {this.y += this.speed;if (this.y > canvas.height) {this.y = -this.size;this.x = Math.random() * canvas.width;}}}// 创建爱心数组const hearts = [];for (let i = 0; i < 100; i++) {hearts.push(new Heart());}// 动画循环function animate() {ctx.clearRect(0, 0, canvas.width, canvas.height);hearts.forEach(heart => {heart.draw();heart.move();});requestAnimationFrame(animate);}animate();// 鼠标互动canvas.addEventListener('mousemove', (e) => {const mouseX = e.clientX;const mouseY = e.clientY;hearts.forEach(heart => {const dx = mouseX - heart.x;const dy = mouseY - heart.y;const distance = Math.sqrt(dx * dx + dy * dy);if (distance < 100) {const angle = Math.atan2(dy, dx);heart.x -= Math.cos(angle) * 2;heart.y -= Math.sin(angle) * 2;}});});</script>
</body></html>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词