写一段烟花动画的js代码

非常好! 这是一段简单的烟花动画的 JavaScript 代码:

``` var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d");

// 用于存储烟花的数组 var fireworks = [];

// 烟花的构造函数 function Firework(x, y) { this.x = x; this.y = y; this.r = Math.random() * 2 + 1; // 烟花的半径 this.vx = Math.random() * 5 - 2.5; // 烟花的水平速度 this.vy = Math.random() * 5 - 2.5; // 烟花的竖直速度 this.hue = Math.random() * 360; // 烟花的色调 this.lifespan = Math.random() * 300 + 100; // 烟花的寿命 this.alpha = 1; // 烟花的透明度 }

// 绘制烟花 Firework.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fillStyle = "hsla(" + this.hue + ", 100%, 50%, " + this.alpha + ")"; ctx.fill(); }

// 更新烟花 Firework.prototype.update = function() { this.x += this.vx; this.y += this.vy; this.alpha -= 0.01; }

// 渲染函数 function render() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布

// 遍历所有烟花 for (var i = 0; i < fireworks.length; i++) { fireworks[i].draw(); fireworks[i].update();

// 如果烟花的寿命已经用完,就从数组中移除它
if (fireworks[i].alpha < 0) {
  fireworks.splice(i, 1);
  i--;
}

}

requestAnimationFrame(render); // 请求浏览器调用渲染函数 }

// 添加新烟花 function addFirework() { // 随机生成烟花的坐标 var x = Math.random() * canvas.width; var y = Math.random()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值