jack parker
jack parker

Reputation: 33

Pulse effect using vanilla JavaScript

Trying to create a pulse effect with a canvas object with plain vanilla javascript. Each function seems to be calling properly and all my values are logging right, but for some reason when the drawBall() function is called in the ballShrink() function nothing happens. I am expecting it to animate to shrink but it doesn't. ballRadius is reducing but no animation occurs. I have my code here and a JSFiddle here https://jsfiddle.net/96hthyw0/

function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        drawBall();
  }

function ballGrow() {
    ballRadius += 1;
    drawBall();
    if (ballRadius === 20)  {
        clearInterval(ballGrowInterval);
        ballShrinkInterval = setInterval(ballShrink, 100);
    } 
}

function ballShrink()   {
    ballRadius -= 1;
    drawBall();
    if (ballRadius === 0)   {
       clearInterval(ballShrinkInterval);
    }
}

function testInterval() {
    ballGrowInterval = setInterval(ballGrow, 100);
}  

testInterval();
draw();

Upvotes: 1

Views: 2154

Answers (1)

winhowes
winhowes

Reputation: 8065

The problem is you're not clearing your last drawing but just adding new drawings on top of the existing one. Here is an updated fiddle: https://jsfiddle.net/96hthyw0/1/ but in short all I did was change your ballShrink function to this:

function ballShrink()   {
  ballRadius -= 1;
  draw(); // clear canvas - note you could add this to ball grow too
  drawBall();
  if (ballRadius === 0) {
    clearInterval(ballShrinkInterval);
  }
}

Upvotes: 4

Related Questions