“动态的白云在飘”这个效果可以通过JavaScript结合HTML5的Canvas API或者WebGL来实现。以下是一个使用Canvas API实现动态白云飘动的基本示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态白云飘动</title>
<style>
canvas {
display: block;
background: #87CEEB; /* 天空蓝 */
}
</style>
</head>
<body>
<canvas id="cloudCanvas" width="800" height="600"></canvas>
<script src="cloud.js"></script>
</body>
</html>
const canvas = document.getElementById('cloudCanvas');
const ctx = canvas.getContext('2d');
// 白云类
class Cloud {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.speed = 0.5 + Math.random() * 1.5; // 随机速度
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fill();
}
update() {
this.x += this.speed;
if (this.x > canvas.width + this.size) {
this.x = -this.size; // 重置云的位置
}
this.draw();
}
}
// 创建多个白云实例
const clouds = [];
for (let i = 0; i < 10; i++) {
const size = 30 + Math.random() * 20;
const x = -size - Math.random() * canvas.width;
const y = 100 + Math.random() * (canvas.height / 2);
clouds.push(new Cloud(x, y, size));
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
clouds.forEach(cloud => cloud.update());
requestAnimationFrame(animate);
}
animate();
canvas
元素,用于绘制白云。Cloud
类,包含位置、大小和速度属性,以及绘制和更新位置的方法。Cloud
实例,分布在画布的不同位置。requestAnimationFrame
实现动画循环,每次循环更新所有白云的位置并重新绘制。希望这个示例能帮助你实现动态白云飘动的效果!
领取专属 10元无门槛券
手把手带您无忧上云