0

I'm able to code animations, I understand keyboard input but I'm struggling to put everything together. I'm basically coding a connect 4 game but I've simplified the problem I'm having.

When I press spacebar it will call movePiece function

function keyboardMove(e){
    switch(e.keyCode) {
    case 32:
        movePiece(0, 0, 1000);
        break;
    }

movePiece() will move a circle from the top of the canvas to the bottom. I want this to happen slowly so I've updated the Y position by 0.1 every 25 milliseconds

function movingPiece(x, startY, endY){

var y = startY;

    while(y<endY)
    {
        setInterval(function(){
            b_ctx.globalCompositeOperation="destination-over";
            b_ctx.fillStyle = "yellow";
            b_ctx.beginPath();
            b_ctx.arc(x, startY, 45, 0, Math.PI*2, true);
            b_ctx.fill();
        }, 25);

        y+=0.1;
    }
}

The animation doesn't work or at least not visually. I'd appreciate if someone could explain the best way to complete an animation following a keyboard press

1
  • In your code, the while loop sets up all these new intervals in quick succession. 25 ms later, all those intervals run for the first time. And 25 ms later for the second time. And so on. You probably were looking for setTimeout with cumulative delay. Cleaner solution: use requestAnimationFrame and update positions according to time passed between frames, request new frame until animation has finished. Commented May 14, 2017 at 1:45

1 Answer 1

1

Keyboard pressing is irrelevant here - it just calls the function. There are several issues with this code:

  1. Typo in function name
  2. If the circle should ever move, you have to pass y, not startY, as only y is being changed
  3. You have nested loops here, as setInterval is loop itself. It can be stopped using clearInterval(), so "while" isn't necessary
  4. "destination-over" may not be the best choice here.

var c = document.querySelector('#c')
var b_ctx = c.getContext('2d') ;

function movingPiece(x, startY, endY){

var y = startY;

   
    
        var inter = setInterval(function(){
          
            b_ctx.globalCompositeOperation="copy";
            b_ctx.fillStyle = "yellow";
            b_ctx.beginPath();
            b_ctx.arc(x, y, 45, 0, Math.PI*2, true);
            b_ctx.fill();
           y+=0.1;
           if (y>endY) clearInterval(inter)
        }, 25);

       
    
}
movingPiece(0, 0, 1000);
<canvas id="c"></canvas>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.