Aayushi
Aayushi

Reputation: 1816

HTML5 canvas requestAnimationFrame() is not working

I am trying to do a simple animation using window.requestAnimationFrame().Somehow,The function is not getting called recursively and not giving the correct code.The javascript code of my file is:

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();

Here, although the console a is getting printed recursively but the circles are not getting formed.The link to my Codepen is Here.How exactly is requestAnimationFrame() is used?

Upvotes: 0

Views: 4263

Answers (2)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

You have too many issues with your code ...

Here's how it should be done

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}
<canvas id="canvas"></canvas>

apology for not giving any explanation

Upvotes: 5

Littlee
Littlee

Reputation: 4327

you didn't pass canvas and context to animate function when calling 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;
} 

Upvotes: 0

Related Questions