<!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>
JavaScript + HTML5 Canvas 实现互动爱心雨
2025/2/21 3:01:39
来源:https://blog.csdn.net/hl826669/article/details/145635972
浏览:
次
关键词:JavaScript + HTML5 Canvas 实现互动爱心雨
版权声明:
本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。
我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com
热文排行
- Day01_Ajax入门
- RuntimeError: CUDA error: device-side assert triggered
- 爬虫案例3——爬取彩票双色球数据
- 安卓端侧大模型 MLC-LLM 部署全攻略:以 InternLM2.5-1.8B 为例
- 苹果iOS 17.6.1正式推送,有哪些机型值得更新呢?
- CosyVoice 实测,阿里开源语音合成模型,3s极速语音克隆,5分钟带你部署实战
- React Native 应用中预加载 SQLite 数据库的全面指南
- 2024华数杯C题解题思路、参考论文已出(无偿分享)~
- DSP——从入门到放弃系列2——PLL锁相环(持续更新)
- spring 对于 XML 中自定义标签的解析