Canvas 自由落体
作者:互联网
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>炫彩小球自由掉落</title>
<style>
body{margin:0;padding:0;overflow:hidden;}
#title {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 100px;
border-top: 3px solid black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<h1 id="title">shang hai</h1>
</body>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
let particalArray = [];
const numberOfParticales = 300;
const titleElement = document.getElementById('title');
let titleMeasurement = titleElement.getBoundingClientRect();
let title = {
x: titleMeasurement.left,
y: titleMeasurement.top,
width: titleMeasurement.width,
height: 10,
};
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 15 + 1;
this.weight = Math.random() * 1 + 1;
this.directionX = -1;
}
update() {
if (this.y > canvas.height) {
this.y = 0 - this.size;
this.weight = Math.random() * 1 + 1;
this.x = Math.random() * canvas.width * 1.5;
}
this.weight += 0.01;
this.y += this.weight;
this.x += this.directionX;
if (
this.x < title.x + title.width &&
this.x + this.size > title.x &&
this.y < title.y + title.height &&
this.y + this.size > title.y
) {
this.y -= 4;
this.weight *= -0.5;
}
}
draw() {
ctx.fillStyle = `hsl(${this.x}, 100%, 50%)`;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
}
function init() {
particalArray = [];
for (let i = 1; i < numberOfParticales; i += 1) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
particalArray.push(new Particle(x, y));
}
}
init();
function animation() {
ctx.fillStyle = 'rgba(255,255,255,0.09)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particalArray.forEach((particle) => {
particle.update();
particle.draw();
});
requestAnimationFrame(animation);
}
animation();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
titleMeasurement = titleElement.getBoundingClientRect();
title = {
x: titleMeasurement.left,
y: titleMeasurement.top,
width: titleMeasurement.width,
height: 10,
};
init();
});
</script>
</html>
到底了!原创不易,转载请注明出处。
前端的学习不是一蹴而就,不积跬步无以至千里,不积小流无以成江海。持续不断的努力才能让你我有所收获,专业的知识还得到机构去学习,培训机构的设立有其存在的必然性,你钱花对了吗?
不辜负每一份真情,不嘲笑每一个正在努力的人,力所能及的对别人施以援手,每天都要强化自己,洗去铅华才能绽放光芒。
推荐阅读:
小鲨鱼
忍术!猫眼三勾玉
召唤神龙
旋转魔方
拟态小象
标签:Canvas,title,自由落体,ctx,canvas,titleMeasurement,height,width 来源: https://blog.csdn.net/weixin_45820444/article/details/110039553