【问题标题】:HTML5 canvas requestAnimationFrame() is not workingHTML5 画布 requestAnimationFrame() 不起作用
【发布时间】:2017-04-25 10:18:09
【问题描述】:

我正在尝试使用 window.requestAnimationFrame() 做一个简单的动画。不知何故,该函数没有被递归调用,也没有给出正确的代码。我文件的 javascript 代码是:

function OilPainting(){
  this.initialize=function(){
     var x=100;
    var canvas=document.getElementById("canvas");
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight;

  var context=canvas.getContext('2d');
    animate(canvas,context);
  }
}

var x=100;
var animate=function(canvas,context){
   window.requestAnimationFrame(animate);
  console.log("a");
  //console.log("a");
  /*for(var i=0;i<1;i++){
    var x=Math.random()*window.innerWidth;
    var y=Math.random()*window.innerHeight;
  context.beginPath();
  context.arc(x,y,30,0,2*Math.PI);
  context.stroke();
  //console.log("here");
    x+=1;*/

  context.beginPath();
  context.arc(x,100,30,0,2*Math.PI);
  context.clearRect(0,0,innerWidth,innerHeight);
  //console.log(x);
  context.stroke();
  x+=100;
 // console.log(x);
  }  
var app=new OilPainting();
app.initialize();

在这里,虽然控制台 a 正在递归打印,但圆圈没有形成。我的 Codepen 的链接是 Here。requestAnimationFrame() 究竟是如何使用的?

【问题讨论】:

  • requestAnimationFrame 的第一个参数是时间。应该是function animated(time){ requestAnimationFrame(animate);...

标签: javascript html canvas


【解决方案1】:

你的代码有太多问题...

应该这样做

var x = 100;

function OilPainting() {
    this.initialize = function() {
        var canvas = document.getElementById("canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var context = canvas.getContext('2d');
        animate(canvas, context);
    }
}

var animate = function(canvas, context) {
    //console.log("a");
    context.clearRect(0, 0, innerWidth, innerHeight);
    context.beginPath();
    context.arc(x, 100, 30, 0, 2 * Math.PI);
    context.stroke();
    x += 1;
    
    requestAnimationFrame(function() {
        animate(canvas, context);
    });
}

var app = new OilPainting();
app.initialize();
body{margin:0;overflow:hidden}canvas{border:1px solid #d3d3d3}
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

抱歉没有给出任何解释

【讨论】:

  • canvas 可以通过context.canvas 获得时,为什么要传递它
  • @Blindman67 是的,我知道。只是为了保持现状(那种):)
  • 谢谢!! @ℊααnd,canvas 可以作为 context.canvas 使用吗?
  • @aayushi 不客气!是的,可以使用 context.canvas
【解决方案2】:

您在调用requestAnimationFrame 时没有将画布和上下文传递给动画函数

var animate=function(canvas,context){

  window.requestAnimationFrame(function() {
    animate(canvas, context)
  });

  console.log("a");
  context.beginPath();
  context.arc(x,100,30,0,2*Math.PI);
  //console.log(x);
  context.stroke();
  x+=100;
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多