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>
      canvas {
        border: 1px solid #444;
        /* margin: 0 auto; */
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="500px" height="500px"
      >浏览器版本过低,请升级最新版本谷歌浏览器(只有低版本浏览器才会显示标签内的文字)</canvas
    >
  </body>
  <script>
    //获取canvas画布
    var canvas = document.querySelector('#canvas');
    // //获取上下文
    var ctx = canvas.getContext('2d');
    var w = 500;
    var h = 500;
    //第一步:创建小球类
    var text = '12';
    function Ball(x, y) {
      this.x = x;
      this.y = y;
      this.r = 30;
      this.color = random_color();
    }
    //定义小球显示方法
    Ball.prototype.show = function () {
      this.r--; //半径越来越小
      drawCircle(this.x, this.y, this.r, this.color);
    };

    //鼠标移动事件,创建并加入小球数组
    var ballArr = [];
    window.onmousemove = function (e) {
      var ball = new Ball(e.x, e.y);
      ballArr.push(ball);
      ball.show();
    };
    //让创建好的逐渐变小直至删除
    setInterval(() => {
      ctx.clearRect(0, 0, w, h); //先清除画布
      for (var i = 0; i < ballArr.length; i++) {
        var ball = ballArr[i];
        if (ball.r <= 0) {
          ballArr.splice(i, 1);
        } else {
          ball.show();
        }
      }
    }, 20);

    //封装画直线
    function drawLine(x1, y1, x2, y2, color, width) {
      //开启一条路径
      ctx.beginPath();
      // //确定起始点
      ctx.moveTo(x1, y1);
      // //到哪里结束
      ctx.lineTo(x2, y2);
      // //关闭路径
      ctx.closePath();
      //设置颜色
      ctx.strokeStyle = color;
      //设置线宽
      ctx.lineWidth = width;
      //着色(如果要设置颜色和线宽,务必在着色之前设置)
      ctx.stroke();
    }

    //封装画实心圆
    function drawCircle(x, y, r, color, text) {
      ctx.beginPath();
      ctx.arc(x, y, r, 0, Math.PI * 2, true);
      ctx.fillStyle = color;
      ctx.fill();
    }

    //封装产生随机数
    function random_num(num) {
      return parseInt(Math.random() * num);
    }
    //生成rgb随机颜色
    function random_color() {
      var rgb =
        'rgb(' +
        Math.floor(Math.random() * 255) +
        ',' +
        Math.floor(Math.random() * 255) +
        ',' +
        Math.floor(Math.random() * 255) +
        ')';
      console.log(rgb);
      return rgb;
    }
  </script>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值