帮我写一个js的烟花代码
时间: 2023-03-15 18:20:51 浏览: 122
我可以给你一个简单的例子:var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var W = window.innerWidth;
var H = window.innerHeight; //设置烟花爆炸的坐标
var mx = W/2;
var my = H/2; //画布尺寸
canvas.width = W;
canvas.height = H; //创建烟花对象
var fireworks = [];
var particles = []; //存放颜色的数组
var hue = 120; //设置重力加速度
var gravity = 0.2; //创建烟花函数
function Firework(sx, sy, tx, ty){
//起始坐标
this.x = sx;
this.y = sy;
//结束坐标
this.sx = tx;
this.sy = ty;
//半径
this.radius = 2;
//烟花速度
this.vx = (tx - sx) / 20;
this.vy = (ty - sy) / 20;
//alpha值
this.alpha = 1;
//色彩
this.hue = hue;
//状态
this.status = 1;
//更新函数
this.update = function(){
//若烟花处于活动状态
if(this.status == 1){
//更新位置
this.x += this.vx;
this.y += this.vy;
//更新alpha值
this.alpha -= 0.02;
//若alpha值小于0,则将烟花状态置为0
if(this.alpha < 0){
this.status = 0;
}
}
//绘制烟花
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = "hsla(" + this.hue + ",100%,50%, "+this.alpha+")";
ctx.fill();
}
} //创建烟花粒子函数
function Particle(x, y){
//x,y坐标
this.x = x;
this.y = y;
//半径
this.radius = 1.2;
//角度
this.angle = Math.random() * 360;
//色彩
this.hue = hue;
//随机速度
this.vx = Math.random() * 6 - 3;
this.vy = Math.random() * 6 - 3;
//重力加速度
this.gravity = gravity;
//alpha值
this.alpha = 1;
//状态
this.status = 1;
//更新函数
this.update = function(){
//若烟花处于活动状态
if(this.status == 1){
//更新位置
this.x += this.vx;
this.y += this.vy;
//更新速度
this.vx += Math.random() * 0.2 - 0.1;
this.vy += Math.random() * 0.2 - 0.1;
//更新重力加速度
this.vy += this.gravity;
//更新alpha值
this.alpha -= 0.02;
//若alpha值小于0,则将烟花状态置为0
if(this.alpha < 0){
this.status = 0;
}
}
//绘制烟花粒子
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = "hsla(" + this.hue + ",100%,50%, "+this.alpha+")";
ctx.fill();
}
} //创建烟花函数
function createFireworks(){
//将烟花对象添加到数组中
fireworks.push(new Firework(mx, my, mx + Math.random() * 30 - 15, my + Math.random() * 30 - 15));
//改变hue值
hue += 0.3;
} //创建烟花粒子函数
function createParticles(x, y){
//循环创建50个烟花粒子
for(var i = 0; i < 50; i++){
particles.push(new Particle(x,y));
}
} //更新函数
function update(){
//清除画布
ctx.clearRect(0, 0, W, H);
//绘制烟花
for(var i = 0; i < fireworks.length; i++){
//更新烟花
fireworks[i].update();
//若烟花状态为0,则创建烟花粒子
if(fireworks[i].status == 0){
createParticles(fireworks[i].sx, fireworks[i].sy);
//移除烟花
fireworks.splice(i, 1);
}
}
//绘制烟花粒子
for(var i = 0; i < particles.length; i++){
//更新烟花粒子
particles[i].update();
//若烟花状态为0,则移除烟花粒子
if(particles[i].status == 0){
particles.splice(i, 1);
}
}
//每隔10ms创建一个烟花
if(timer % 10 == 0){
createFireworks();
}
//
阅读全文