Canvas 烟花点击特效

效果图

附上代码 

HTML

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>点击烟花</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        body {
            width: 100vw;
            height: 100vh;
            overflow: hidden;
        }

        #canvas {
            background-color: #000000;
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
</body>
<script src="./index.js"></script>

</html>

Javascript

/** @type {HTMLCanvasElement} */
const can = document.getElementById("canvas");

can.width = window.innerWidth;
can.height = window.innerHeight;

const ctx = can.getContext("2d");

// 定义小球
class Ball {
  constructor(x, y, dirX, dirY, color) {
    // 起始位置
    this.x = x;
    this.y = y;
    // 爆炸方向
    this.dirX = dirX;
    this.dirY = dirY;
    // 大小
    this.radius = 3;
    // 透明度
    this.opacity = 4;
    // 颜色
    this.color = color;
  }

  //   绘画小球
  draw() {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fill();
    ctx.closePath();
  }
  //   绘制路线
  update() {
    this.dirX *= 0.99;
    this.dirY *= 0.99;
    this.dirY += 0.1;
    this.x += this.dirX;
    this.y += this.dirY;
    this.opacity -= 0.01;
    this.draw();
  }
}

const balls = [];

function animate() {
  ctx.fillStyle = "rgba(0,0,0,0.05)";
  ctx.fillRect(0, 0, can.width, can.height);
  for (let index = 0; index < balls.length; index++) {
    const element = balls[index];
    element.update();
    // 透明度小于0.1就删除
    if (element.opacity < 0.1) {
      balls.splice(index, 1);
    }
  }

  // 重复执行动画
  requestAnimationFrame(animate);
}
animate();

can.addEventListener("click", (e) => {
  // 小球数量
  const nums = 400;
  // 每一个偏移弧度
  const hd = (Math.PI * 2) / nums;
  // 循环创建小球和爆炸区间
  for (let index = 0; index < nums; index++) {
    balls.push(
      new Ball(
        // 位置
        e.x,
        e.y,
        // 爆炸方向
        Math.cos(hd * index) * (Math.random() * 20),
        Math.sin(hd * index) * (Math.random() * 20),
        // 颜色
        `hsl(${Math.random() * 360},50%,50%)`
      )
    );
  }
});

Canvas 学习作业完成

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值