全网canvas基础圆形移动

126 阅读1分钟

html

<canvas id="canvas"></canvas>

js

<script>
  var canvas = document.getElementById('canvas')
  canvas.width = 400
  canvas.height = 400
  var ctx = canvas.getContext('2d')
  var x = 100
  setInterval(function() {
   //自增
    x++;
    // 清除整个画面
    ctx.clearRect(0,0, canvas.width, canvas.height);
    // 创建一个图片对象
    ctx.beginPath()
    // 绘制弧形
    ctx.arc(x, 200,50,0,Math.PI*2, true)
    // 填充
    ctx.fillStyle= "navy";
    ctx.fill();
    // 封闭线段
    ctx.closePath()
  },20)
</script>

用面向对象的方法,来移动小球

<script src="./underscore-min.js"></script>
<script>
  var canvas = document.getElementById('canvas')
  canvas.width = 400
  canvas.height = 400
  var ctx = canvas.getContext('2d')
  var x = 100
  // 小球类
  function Ball(x,y, r,color,speed) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = color;
    this.speed = speed;
    // x的移动大小
    this.dX = Math.random() *10 -5;  // -5~5
    this.dY = Math.random() *10 -5;  // -5~5
    // 半径的缩减
    this.dR = Math.random() *2+1 // 1~2
    // 将实例化的小球入到数组里面
    ballArray.push(this)
  }
  // 小球的原型
  Ball.prototype = {
    updated: function () {
      this.x += this.dX;
      this.y += this.dY;
      this.r -= this.dR;
      if(this.r <= 0) {
        this.r = 0.1;
        // 用到了underscore-min.js 
        ballArray = _.without(ballArray, this)
      }
    },
    // 渲染自己
    render: function () {
      // 绘制圆的api
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, true)
      ctx.fillStyle = this.color;
      ctx.fill()
    }
  }
  var ballArray = new Array()
  
  setInterval(function() {
    // 清除画布
    ctx.clearRect(0,0, canvas.width,canvas.height)
    for(var i=0; i<ballArray.length; i++) {
      // 更新小球
      ballArray[i].updated();
      // 所以要验证这个对象在
      if(ballArray[i]) {
        // 渲染小球
        ballArray[i].render();
      }
    }
  },20);
  // 监听
  canvas.addEventListener("mousemove", function(event){
    new Ball(event.offsetX, event.offsetY, 50, "red")
  })
</script>