用javascript写一个烟花

好的,这是一个使用 JavaScript 制作烟花的简单例子:

``` const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d');

// 设置画布的大小 canvas.width = window.innerWidth; canvas.height = window.innerHeight;

// 定义烟花对象 function Firework() { // 随机设置烟花的起始位置 this.x = Math.random() * canvas.width; this.y = canvas.height;

// 随机设置烟花的颜色 this.color = hsl(${Math.random() * 360}, 100%, 50%);

// 设置烟花的半径 this.radius = Math.random() * 4 + 1;

// 随机设置烟花的上升速度 this.vy = Math.random() * -3 - 4; }

// 在画布上绘制烟花 Firework.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); };

// 更新烟花的位置 Firework.prototype.update = function() { this.y += this.vy; };

// 创建烟花数组 const fireworks = [];

// 定义绘制函数 function draw() { // 清空画布 ctx.clearRect(0, 0, canvas.width, canvas.height);

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

// 如果烟花移出了画布,就将其从数组中删除
if (fireworks[i].y < 0) {
  fireworks.splice(i, 1);
  i--;
}

}

// 使用 requestAnimationFrame 递归调用 draw 函数,以便在浏览器刷新时继续绘制 requestAnimationFrame(draw); }

// 使用 setInterval 定时生成新的烟花 setInterval(function() { fireworks.push

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值