Why am I getting this burn in effect with oscillating movement in p5.js?

Viewed 28

I have a simple ellipse moving back and forth and I keep getting this sort of "burn in" or "ghost trail" effect. What might be causing this?

Here is the code:

let x = 50;
let y = 50;

function setup() {
  createCanvas(500, 500);
}

function draw() {
  background(0);
  ellipse(x, y, 70, 70);
  x += 1 + (50 * sin(y));
  y += 2;
  if (x >= 500 || y >= 500) {
      x = 50;
      y = 50;
  }
}
1 Answers

Though I don't know what you want your animation to look like, the 'ghosting' is caused by your circle's horizontal position which jumps back and forth between very extreme values, because you calculate the sine of numbers in increments of 2. 2 radians are approximately 114 degrees which is really much. If you want a smooth movement you'd rather use a value of e.g. 0.1. So set up an additional variable which keeps track of the phase.

Here's an example - not p5.js but the concept is the same:

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

let x = 50;
let y = 50;
let counter = 0;

function draw() {
    x = canvas.width / 2 + (50 * Math.sin(counter));
    y += 2;
    if (x >= 500 || y >= 500) {
        x = 50;
        y = 50;
    }
  
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();
    counter += 0.1;
}

setInterval(draw, 100);
<canvas id="canvas" width="400" height="400"></canvas>

Related