炫彩小球demo

<!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>炫彩小球demo</title>
</head>
<body>
  <canvas id='myCanvas'></canvas>
  <script>
    let myCanvas = document.getElementById('myCanvas')
    let ctx = myCanvas.getContext('2d')
    console.log(ctx)
    function Ball(x, y, r){
      this.x = x
      this.y = y
      this.r = r
      this.color = getRandom()
      this.dx = parseInt(Math.random() * 10) - 5
      this.dy = parseInt(Math.random() *  10) - 5
      ballArr.push(this)
    }
    Ball.prototype.render = function(){
      ctx.beginPath()
      ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
      ctx.fillStyle = this.color
      ctx.fill()
    }
    Ball.prototype.update = function(){
      this.x += this.dx
      this.y += this.dy
      this.r -= 0.1
      if(this.r < 0){
        this.remove()
      }
    }
    Ball.prototype.remove = function(){
      for(var i = 0; i < ballArr.length; i++){
        if(ballArr[i] === this){
          ballArr.splice(i, 1)
        }
      }
    }
    function getRandom(){
      var allType = '0,1,2,3,4,5,6,7,8,a,b,c,d,e,f'
      var allTypeArr = allType.split(',')
      var color = '#'
      for(let i = 0; i < 6; i++){
        var random = parseInt(Math.random() * allTypeArr.length)
        color += allTypeArr[random]
      }
      return color
    }
    var ballArr = []
    setInterval(function(){
      ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
      for(let i = 0; i < ballArr.length; i++){
        ballArr[i].update()
        if(ballArr[i]){
          ballArr[i].render()
        }
      }
    }, 20)
    myCanvas.addEventListener('mousemove', function(e){
      new Ball(e.offsetX, e.offsetY, parseInt(Math.random() * 20))
      console.log(ballArr)
    })
  </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值