我正在画布上创建简单的动画。我使用requestanimationframe来控制动画。有3个圆圈。但是我只能看到3个圆圈,动画太快了。我的问题是如何减慢动画速度以及如何显示每一帧。这是我的实况link

const swing = (time) => {
  for(var i = 0; i < 3; i++) {
    circle[i] = new ball();
    circle[i].draw(i, circle[i].color);
  }

  requestAnimationFrame(swing);
}

requestAnimationFrame(swing);
//swing();


function ball(i){
    this.x = random(100, 150);
    this.y = random(40, 60);
    this.radius = 45;
    this.color = getRandomColor(random(1, 30));
    this.strokeText = "m"

    ctx.clearRect(0, 0, el.width, el.height);
    this.draw = function(i, color){
        ctx.beginPath();
        ctx.font="30px Verdana";
        ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
        ctx.fillStyle = color;
        ctx.globalAlpha = 0.5;
        ctx.strokeText(i,i*this.x,this.y);
        ctx.fill();
        ctx.closePath();
    }
}


提前致谢。

编辑:-我正在创建类似这样的内容:-http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010

最佳答案

只是一个简单的示例,让三个球做一些圆周运动:



// refer below
// http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010
const el = document.getElementById('canvas'),
      ctx = el.getContext('2d');
      let circle = [];
el.width = document.body.clientWidth;
el.height = document.body.clientHeight;

const getRandomColor = (i) => {
  let count = 30,
      color = 1,
      hue = (i / count * color) * 360;
  return `hsla(${hue}, 100%, 50%, 1)`
}

for (var i = 0; i < 3; i++) {
  circle[i] = new ball();
}

let angle = 0;
let speed = 0.02;

const swing = (time) => {
  ctx.clearRect(0, 0, el.width, el.height);

  for (var i = 0; i < 3; i++) {
    circle[i].x = circle[i].x + Math.cos(angle) * 1;
    circle[i].y = circle[i].y + Math.sin(angle) * 2;
  }
  for (var i = 0; i < 3; i++) {
    circle[i].draw(i, circle[i].color);
  }
  angle += speed;
  requestAnimationFrame(swing);
}

requestAnimationFrame(swing);
//swing();


function ball(i){
    this.x = random(100, 150);
    this.y = random(40, 60);
    this.radius = 45;
    this.color = getRandomColor(random(1, 30));
    this.strokeText = "m"

    this.draw = function(i, color){
        ctx.beginPath();
        ctx.font="30px Verdana";
        ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
        ctx.fillStyle = color;
        ctx.globalAlpha = 0.5;
        ctx.strokeText(i,i*this.x,this.y);
        ctx.fill();
        ctx.closePath();
    }
}

function random (num1, num2) {
    var max = Math.max(num1, num2);
    var min = Math.min(num1, num2);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

#canvas {
  width: 600px;
  height: 600px;
}

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

09-26 16:31