Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
How to change y position during animation

I'm drawing animated circles inside a canvas, and so far I managed to make it go from left to right inside the canvas. What I need to do is, when the circle reaches it's righmost position, to make it start its path (left to right) again, but in a position below. I'm trying to change it's y position by at least the circle's diameter, so far without success. Any insight on how can I achieve this? Is it better to make it part of the animation, or make the left-right movement a simple loop with a y position change at the end? My code so far is the following:

var canvas3 = document.getElementById("canvas3");

canvas3.width = 300;
canvas3.height = 500;

var c3 = canvas3.getContext("2d");

var radius = 13;
var x = radius;
var y = radius;

var dx = 1;
var dy = 0;

function animate3() {
  requestAnimationFrame(animate3);

  c3.clearRect(0, 0, 300, 500);

  if (x + radius > 300 || x - radius < 0) {
    dx = 0;
    y + y;
  }

  if (y + radius > 500 || y - radius < 0) {
    dy = 0;
  }

  x += dx;
  y += dy;

  c3.beginPath();
  c3.arc(x, y, 12, 0, Math.PI * 2, false);
  c3.stroke();
  c3.fillText(5, x - 3, y + 3);
}

animate3();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I would simply reset the x position and increment the y position like that :

var canvas3 = document.getElementById("canvas3");

canvas3.width = 300;
canvas3.height = 500;

var c3 = canvas3.getContext("2d");

var radius = 13;
var x = radius;
var y = radius;

var dx = 5;
var dy = 0;

function animate3() {
  requestAnimationFrame(animate3);

  c3.clearRect(0, 0, 300, 500);

  if (x + radius > 300 || x - radius < 0) {
    x = radius;
    y += radius;
  }

  if (y + radius > 500 || y - radius < 0) {
    y = radius;
  }

  x += dx;
  y += dy;

  c3.beginPath();
  c3.arc(x, y, 12, 0, Math.PI * 2, false);
  c3.stroke();
  c3.fillText(5, x - 3, y + 3);
}

animate3();
<canvas id="canvas3"/>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!