PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] How to pass object to animation function in JavaScript?

 July 06, 2022     animation, javascript, object, pass-by-reference     No comments   

Issue

I have been trying to make a JavaScript animation of moving circle in HTML Canvas without using global variables. I am using requestAnimationFrame function. Since JavaScript does not support passing variable by reference, I tried creating a Circle class:

class Circle{
  constructor(x, y, dx, dy) //set initial position and velocity of circle
  {
    this.x = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;
  }
}

function moveCircle(circle, other variables)
{
  //clear canvas
  //calculate new position and velocity using circle.x, etc.
  //save new values to the object
  //draw new circle into the canvas

  requestAnimationFrame(moveCircle);
}

function button()//function called after click on button
{
  //initial settings of canvas, intial condition

  circle = new Circle(x, y, dx, dy);
  moveCircle(circle, other vars);
}

This makes one frame and then throws error "Cannot read property 'x' of undefined". What am I doing wrong? Is there any other way of doing this, while avoiding global variables?


Solution

First of all, you don't need to create a class you can just pass the coordinates in an object or as separate arguments. Secondly you should use Function#bind on requestAnimationFrame to pass the same arguments to next call.

Example using object:

function moveCircle(circle) {
  console.log(circle.x);
  if (circle.x) {
    circle.x -= circle.dx;
    requestAnimationFrame(moveCircle.bind(null, circle));
  }
}

function button() {
  moveCircle({
    x: 500,
    y: 0,
    dx: 20,
    dy: 0
  });
}

button();

Example without object:

function moveCircle(x, dx) {
  console.log(x);
  if (x) {
    requestAnimationFrame(moveCircle.bind(null, x - dx, dx));
  }
}

function button() {
  moveCircle(500, 20);
}

button();



Answered By - nick zoum
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing