canvas实现烟花的示例代码


Posted in HTML / CSS onJanuary 16, 2020

前言:马上过年了,我打算在后台里面偷偷地埋个新春祝福+放烟花的彩蛋。项目是基于react+typescript的,因此最后封装成了一个组件,设置好开启时间就可以显示了。

目录结构

目录结构大致如下

canvas实现烟花的示例代码

我们将烟花分为两个阶段,一个是未炸开持续上升时期,另一个是炸开后分散的时期。
其中Vector表示一个坐标,Particle表示一个烟花的亮点,Firewor表示烟花未炸开时持续上升的亮点。index.tsx就是组件了,绘制了canvas,并执行了动画。

Vector

这个坐标就很简单,后面涉及到位置的变更都可以使用它的add方法进行偏移操作

export default class Vector {
    constructor(public x: number, public y: number) {}
    add(vec2: {x: number; y: number}) {
        this.x = this.x + vec2.x;
        this.y = this.y + vec2.y;
    }
}

Particle

初始创建的时候给个坐标,后续每次更新的时候控制y坐标下落,gravity变量就是下落的值。timeSpan用于控制烟花展示的时长

import Vector from './Vector';
export default class Particle {
    pos: Vector = null;
    vel: {x: number; y: number} = null;
    dead: boolean = false;
    start: number = 0;
    ctx: CanvasRenderingContext2D = null;
    constructor(pos: {x: number; y: number}, vel: {x: number; y: number}, ctx: CanvasRenderingContext2D) {
        this.pos = new Vector(pos.x, pos.y);
        this.vel = vel;
        this.dead = false;
        this.start = 0;
        this.ctx = ctx;
    }
    update(time: number, gravity: number) {
        let timeSpan = time - this.start;

        if (timeSpan > 500) {
            this.dead = true;
        }

        if (!this.dead) {
            this.pos.add(this.vel);
            this.vel.y = this.vel.y + gravity;
        }
    }

    draw() {
        if (!this.dead) {
            this.drawDot(this.pos.x, this.pos.y, Math.random() > 0.5 ? 1 : 2);
        }
    }
    drawDot(x: number, y: number, size: number) {
        this.ctx.beginPath();
        this.ctx.arc(x, y, size, 0, Math.PI * 2);
        this.ctx.fill();
        this.ctx.closePath();
    }
}

Firework

生成随机的hsl颜色,hsl(' + rndNum(360) + ', 100%, 60%);Firework每次上升的距离是一个递减的过程,我们初始设置一个上升的距离,之后每次绘制的时候,这个距离减gravity,当距离小于零的时候,说明该出现烟花绽放的动画了。

import Vector from './Vector';
import Particle from './Particle';
let rnd = Math.random;
function rndNum(num: number) {
    return rnd() * num + 1;
}
export default class Firework {
    pos: Vector = null;
    vel: Vector = null;
    color: string = null;
    size: number = 0;
    dead: boolean = false;
    start: number = 0;
    ctx: CanvasRenderingContext2D = null;
    gravity: number = null;
    exParticles: Particle[] = [];
    exPLen: number = 100;
    rootShow: boolean = true;
    constructor(x: number, y: number, gravity: number, ctx: CanvasRenderingContext2D) {
        this.pos = new Vector(x, y);
        this.vel = new Vector(0, -rndNum(10) - 3);
        this.color = 'hsl(' + rndNum(360) + ', 100%, 60%)';
        this.size = 4;
        this.dead = false;
        this.start = 0;
        this.ctx = ctx;
        this.gravity = gravity;
    }
    update(time: number, gravity: number) {
        if (this.dead) {
            return;
        }

        this.rootShow = this.vel.y < 0;

        if (this.rootShow) {
            this.pos.add(this.vel);
            this.vel.y = this.vel.y + gravity;
        } else {
            if (this.exParticles.length === 0) {
                for (let i = 0; i < this.exPLen; i++) {
                    let randomR = rndNum(5);
                    let randomX = -rndNum(Math.abs(randomR) * 2) + Math.abs(randomR);
                    let randomY =
                        Math.sqrt(Math.abs(Math.pow(randomR, 2) - Math.pow(randomX, 2))) *
                        (Math.random() > 0.5 ? 1 : -1);
                    this.exParticles.push(new Particle(this.pos, new Vector(randomX, randomY), this.ctx));
                    this.exParticles[this.exParticles.length - 1].start = time;
                }
            }
            let numOfDead = 0;
            for (let i = 0; i < this.exPLen; i++) {
                let p = this.exParticles[i];
                p.update(time, this.gravity);
                if (p.dead) {
                    numOfDead++;
                }
            }

            if (numOfDead === this.exPLen) {
                this.dead = true;
            }
        }
    }

    draw() {
        if (this.dead) {
            return;
        }

        this.ctx.fillStyle = this.color;
        if (this.rootShow) {
            this.drawDot(this.pos.x, this.pos.y, this.size);
        } else {
            for (let i = 0; i < this.exPLen; i++) {
                let p = this.exParticles[i];
                p.draw();
            }
        }
    }
    drawDot(x: number, y: number, size: number) {
        this.ctx.beginPath();

        this.ctx.arc(x, y, size, 0, Math.PI * 2);
        this.ctx.fill();

        this.ctx.closePath();
    }
}

FireworkComponent

组件本身就很简单了,生成和绘制Firework。我们在这里面可以额外加一些文字

import React from 'react';
import Firework from './Firework';
import {autobind} from 'core-decorators';
let rnd = Math.random;
function rndNum(num: number) {
    return rnd() * num + 1;
}
interface PropTypes {
    onClick?: () => void;
}
@autobind
class FireworkComponent extends React.Component<PropTypes> {
    canvas: HTMLCanvasElement = null;
    ctx: CanvasRenderingContext2D = null;
    snapTime: number = 0;
    fireworks: Firework[] = [];
    gravity: number = 0.1;
    componentDidMount() {
        this.canvas = document.querySelector('#fireworks');
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
        this.ctx = this.canvas.getContext('2d');
        this.init();
        this.draw();
    }

    init() {
        let numOfFireworks = 20;
        for (let i = 0; i < numOfFireworks; i++) {
            this.fireworks.push(new Firework(rndNum(this.canvas.width), this.canvas.height, this.gravity, this.ctx));
        }
    }

    update(time: number) {
        for (let i = 0, len = this.fireworks.length; i < len; i++) {
            let p = this.fireworks[i];
            p.update(time, this.gravity);
        }
    }
    draw(time?: number) {
        this.update(time);

        this.ctx.fillStyle = 'rgba(0,0,0,0.3)';

        this.ctx.fillStyle = 'rgba(0,0,0,0)';
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

        this.ctx.font = 'bold 30px cursive';
        this.ctx.fillStyle = '#e91818';
        let text = 'XX项目组给您拜个早年!';
        let textWidth = this.ctx.measureText(text);
        this.ctx.fillText(text, this.canvas.width / 2 - textWidth.width / 2, 200);
        text = '在新年来临之际,祝您:';
        textWidth = this.ctx.measureText(text);
        this.ctx.fillText(text, this.canvas.width / 2 - textWidth.width / 2, 260);
        text = '工作顺利,新春快乐!';
        this.ctx.font = 'bold 48px STCaiyun';
        this.ctx.fillStyle = 'orangered';
        textWidth = this.ctx.measureText(text);
        this.ctx.fillText(text, this.canvas.width / 2 - textWidth.width / 2, 340);
        this.ctx.fillStyle = 'gray';
        this.ctx.font = '18px Arial';
        text = '点击任意处关闭';
        textWidth = this.ctx.measureText(text);
        this.ctx.fillText(text, this.canvas.width - 20 - textWidth.width, 60);
        this.snapTime = time;

        this.ctx.fillStyle = 'blue';
        for (let i = 0, len = this.fireworks.length; i < len; i++) {
            let p = this.fireworks[i];
            if (p.dead) {
                p = this.fireworks[i] = new Firework(
                    rndNum(this.canvas.width),
                    this.canvas.height,
                    this.gravity,
                    this.ctx
                );
                p.start = time;
            }
            p.draw();
        }

        window.requestAnimationFrame(this.draw);
    }

    render() {
        return (
            <canvas
                id="fireworks"
                onClick={this.props.onClick}
                style={{position: 'fixed', zIndex: 99, background: 'rgba(0,0,0, 0.8)'}}
                width="400"
                height="400"></canvas>
        );
    }
}
export default FireworkComponent;

大致效果

canvas实现烟花的示例代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

HTML / CSS 相关文章推荐
让IE可以变相支持CSS3选择器
Jan 21 HTML / CSS
如何用css3实现switch组件开关的方法
Feb 09 HTML / CSS
css3 transform过渡抖动问题解决
Oct 23 HTML / CSS
HTML5标签小集
Aug 02 HTML / CSS
HTML5之WebGL 3D概述(下)—借助类库开发及框架介绍
Jan 31 HTML / CSS
html5画布旋转效果示例
Jan 27 HTML / CSS
HTML5 Canvas中绘制椭圆的4种方法
Apr 24 HTML / CSS
详解canvas绘图时遇到的跨域问题
Mar 22 HTML / CSS
浅谈Html5多线程开发之WebWorkers
May 02 HTML / CSS
浅析canvas元素的html尺寸和css尺寸对元素视觉的影响
Jul 22 HTML / CSS
关于iframe跨域使用postMessage的实现
Oct 29 HTML / CSS
CSS3 菱形拼图实现只旋转div 背景图片不旋转功能
Mar 30 HTML / CSS
使用iframe+postMessage实现页面跨域通信的示例代码
Jan 14 #HTML / CSS
Html5跳转到APP指定页面的实现
Jan 14 #HTML / CSS
html5自动播放mov格式视频的实例代码
Jan 14 #HTML / CSS
html5响应式开发自动计算fontSize的方法
Jan 13 #HTML / CSS
html5 制作地图当前定位箭头的方法示例
Jan 10 #HTML / CSS
详解HTML5 Canvas标签及基本使用
Jan 10 #HTML / CSS
HTML5自定义mp3播放器源码
Jan 06 #HTML / CSS
You might like
Smarty模板快速入门
2007/01/04 PHP
PHP求最大子序列和的算法实现
2011/06/24 PHP
php中的抽象方法和抽象类
2017/02/14 PHP
JavaScript Event学习第七章 事件属性
2010/02/07 Javascript
js location.replace与location.reload的区别
2010/09/08 Javascript
jquery 操作表格实现代码(多种操作打包)
2011/03/20 Javascript
基于JQuery 滑动与动画的说明介绍
2013/04/18 Javascript
js添加千分位的实现代码(超简单)
2016/08/01 Javascript
js判断数组key是否存在(不用循环)的简单实例
2016/08/03 Javascript
layui的table中显示图片方法
2018/08/17 Javascript
@angular前端项目代码优化之构建Api Tree的方法
2018/12/24 Javascript
微信小程序实现弹出菜单动画
2019/06/21 Javascript
浅谈javascript错误处理
2019/08/11 Javascript
对layui中table组件工具栏的使用详解
2019/09/19 Javascript
解决vue打包报错Unexpected token: punc的问题
2020/10/24 Javascript
python中sets模块的用法实例
2014/09/30 Python
Python中装饰器的一个妙用
2015/02/08 Python
Python使用shelve模块实现简单数据存储的方法
2015/05/20 Python
Python3一行代码实现图片文字识别的示例
2018/01/15 Python
Python实现随机生成手机号及正则验证手机号的方法
2018/04/25 Python
在win10和linux上分别安装Python虚拟环境的方法步骤
2019/05/09 Python
python解释器spython使用及原理解析
2019/08/24 Python
Python多线程爬取豆瓣影评API接口
2019/10/22 Python
丝芙兰法国官网:SEPHORA法国
2016/09/01 全球购物
德国柯吉澳趣味家居:Koziol
2017/08/24 全球购物
全球性的奢侈品梦工厂:Forzieri(福喜利)
2019/02/20 全球购物
Crocs波兰官方商店:女鞋、男鞋、童鞋、洞洞鞋
2019/10/08 全球购物
杭州-DOTNET笔试题集
2013/09/25 面试题
物流专业大学应届生求职信
2013/11/03 职场文书
外企求职信范文分享
2013/12/31 职场文书
高中生评语大全
2014/04/25 职场文书
财会专业毕业生自荐信
2014/07/09 职场文书
农村党员对照检查材料
2014/09/24 职场文书
教师培训简讯
2015/07/20 职场文书
《钢铁是怎样炼成的》高中读后感
2019/08/07 职场文书
Html5同时支持多端sdk的小技巧
2021/11/17 HTML / CSS