canvas下雨打雷效果

canvas下雨打雷效果

废话不多说,代码走起

*html部分*
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <title>canvas下雨打雷效果</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body onresize="_pexresize()">
    <canvas id="dowebok" width="1280" height="720"></canvas>
    <script src="js/script.js"></script>
</body>

</html>
body {
   
	margin: 0;
	background: #000;
}

canvas {
   
	background: url("../images/img1.jpg");
	background-size: cover;
	background-repeat: no-repeat;
	background-position: center center;<
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你提供一个基本的实现思路: 1. 首先创建一个 canvas 元素,并获取其上下文对象。 2. 定义一个 raindrop 类,包括下落速度、位置、大小等属性,以及绘制自己的方法。 3. 创建一个数组来存储多个 raindrop 实例,可以在页面加载时初始化一些 raindrop 对象。 4. 使用 setInterval 或 requestAnimationFrame 循环调用一个函数,用于更新 raindrop 实例的位置,并重新绘制整个画布。 5. 在每次更新 raindrop 实例位置时,可以根据一定的概率来生成新的 raindrop 实例,从而实现下雨效果。 下面是一个简单的示例代码,你可以参考一下: ```html <canvas id="canvas"></canvas> ``` ```javascript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // 雨滴类 class Raindrop { constructor() { this.x = Math.random() * canvas.width; // 随机位置 this.y = -Math.random() * canvas.height; // 从屏幕顶部开始下落 this.speed = Math.random() * 5 + 5; // 下落速度 this.size = Math.random() * 2 + 1; // 大小 } // 绘制雨滴 draw() { ctx.beginPath(); ctx.strokeStyle = '#fff'; ctx.lineWidth = this.size; ctx.moveTo(this.x, this.y); ctx.lineTo(this.x, this.y + this.size * 10); ctx.stroke(); } // 更新雨滴位置 update() { this.y += this.speed; if (this.y > canvas.height) { // 超出屏幕则重新开始下落 this.y = -Math.random() * canvas.height; } } } const raindrops = []; // 初始化一些雨滴 for (let i = 0; i < 100; i++) { raindrops.push(new Raindrop()); } function draw() { // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height); // 更新并绘制所有雨滴 raindrops.forEach((raindrop) => { raindrop.update(); raindrop.draw(); }); // 根据一定概率生成新雨滴 if (Math.random() < 0.1) { raindrops.push(new Raindrop()); } } // 循环调用 draw 函数 setInterval(draw, 30); ``` 这个示例代码可能还有一些不足的地方,你可以根据自己的需求进行改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值