canvas炫彩小球

效果:
请添加图片描述
代码:

<!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>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    body {
      background-color: black;
      overflow: hidden;
    }
  </style>
</head>
<body>
  <canvas id="canvas">
    你的浏览器暂不支持canvas
  </canvas>
</body>
<script>
  const myCanvas = document.querySelector('#canvas');
  // 获取上下文
  const ctx = myCanvas.getContext('2d');
  
  // 设置画布和屏幕一样大小
  myCanvas.width = document.documentElement.clientWidth;
  myCanvas.height = document.documentElement.clientHeight;

  // 用于存放创建出来的小球实例
  const ballsArr = [];

  // 小球类初始化数据
  function Ball(x,y){
    this.x = x;
    this.y = y;
    this.r = 20;
    this.dx = parseInt(Math.random() * 18) - 9;
    this.dy = parseInt(Math.random() * 18) - 9;
    this.color = 'rgba('+parseInt(Math.random() * 256)+','+parseInt(Math.random() * 256)+','+parseInt(Math.random() * 256)+',0.8)';
    // 将创建好的小球对象放入数组
    ballsArr.push(this);
  }

  // 小球的画圆
  Ball.prototype.render = function(){
    ctx.beginPath();
    ctx.arc(this.x,this.y,this.r,0,Math.PI * 2,true);
    ctx.closePath();
    ctx.fillStyle = this.color;
    ctx.fill();
  }

  // 小球的路径更新以及半径减小
  Ball.prototype.update = function(){
    this.x += this.dx;
    this.y += this.dy;
    this.r--;
    if (this.r <= 0) {
      this.goDie();
    }
  }

  // 当小球的半径小于等于0时,清除该小球
  Ball.prototype.goDie = function(){
    for (let index = 0; index < ballsArr.length; index++) {
      if (this === ballsArr[index]) {
        ballsArr.splice(index,1)
      }
    }
  }

  // 当鼠标滑动时创建对应鼠标位置的小球
  myCanvas.onmousemove = function(event){
    new Ball(event.clientX,event.clientY);
  }

  setInterval(()=>{
    // 清屏
    ctx.clearRect(0,0,myCanvas.width,myCanvas.height);

    for (let index = 0; index < ballsArr.length; index++) {
      ballsArr[index].update();
      ballsArr[index] && ballsArr[index].render();
    }
  },20);
</script>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值