canvas实现烟花特效

看过我之前博客的人一定都知道我对canvas赞不绝口,没看过?那就看看下面这篇吧,总结一下对canvas的使用心得就是盘它!

实现效果:

 

代码如下,注释已写:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>烟花爆炸动画</title>
    <style>
        body {
            padding: 0;
            margin: 0;
            overflow: hidden;
            background-color: black;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }
    </styl
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Canvas可以实现很多有趣的特效,包括烟花特效。下面是一个简单的Canvas烟花特效制作步骤: 1. 创建Canvas画布和一个数组,用来存储烟花粒子。 ```javascript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const particles = []; ``` 2. 定义一个Particle类,用来创建烟花粒子。注意每个粒子都有一个随机的颜色。 ```javascript class Particle { constructor(x, y) { this.x = x; this.y = y; this.vx = Math.random() * 5 - 2.5; this.vy = Math.random() * 5 - 2.5; this.color = `rgb(${Math.round(Math.random() * 255)}, ${Math.round(Math.random() * 255)}, ${Math.round(Math.random() * 255)})`; this.radius = 3; this.life = 100; } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); } update() { this.x += this.vx; this.y += this.vy; this.vx *= 0.97; this.vy *= 0.97; this.radius -= 0.05; this.life--; } } ``` 3. 创建一个函数,用来在点击Canvas时创建一个烟花。 ```javascript function createFirework(x, y) { for (let i = 0; i < 50; i++) { particles.push(new Particle(x, y)); } } ``` 4. 在Canvas上监听鼠标点击事件,并在点击时创建一个烟花。 ```javascript canvas.addEventListener('click', (e) => { createFirework(e.clientX, e.clientY); }); ``` 5. 创建一个动画循环函数,用来更新和绘制所有的烟花粒子。 ```javascript function loop() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (let i = 0; i < particles.length; i++) { particles[i].draw(); particles[i].update(); if (particles[i].life <= 0) { particles.splice(i, 1); i--; } } requestAnimationFrame(loop); } ``` 6. 最后启动动画循环函数。 ```javascript loop(); ``` 现在你就可以在Canvas上看到一个简单的烟花特效了。你可以根据需要调整粒子的数量、速度、颜色和寿命等参数,以创建更多的烟花效果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值