使用JavaScript?+?HTML5?Canvas實現(xiàn)互動愛心雨完整代碼
更新時間:2025年03月15日 11:27:32 作者:jackzhuoa
canvas是HTML5中推出的新功能,可以在頁面上生成一個畫布,使用js可以在畫布上繪制一些圖形,這篇文章主要介紹了使用JavaScript?+?HTML5?Canvas實現(xiàn)互動愛心雨的相關(guān)資料,需要的朋友可以參考下
實例代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>情人節(jié)快樂!</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;
}
}
}
// 創(chuàng)建愛心數(shù)組
const hearts = [];
for (let i = 0; i < 100; i++) {
hearts.push(new Heart());
}
// 動畫循環(huán)
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>效果圖

總結(jié)
到此這篇關(guān)于使用JavaScript + HTML5 Canvas實現(xiàn)互動愛心雨的文章就介紹到這了,更多相關(guān)JS+HTML5 Canvas實現(xiàn)互動愛心雨內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
KnockoutJS 3.X API 第四章之?dāng)?shù)據(jù)控制流with綁定
這篇文章主要介紹了KnockoutJS 3.X API 第四章之?dāng)?shù)據(jù)控制流with綁定的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-10-10
通過Tabs方法基于easyUI+bootstrap制作工作站
本教程給大家介紹如何制作easyUI+bootstrap工作站,主要學(xué)習(xí)tabs方法,本文介紹非常詳細,具有參考借鑒價值,需要的朋友參考下吧2016-03-03

