Search code examples
javascripthtmlcanvasmove

How do I move an element on a canvas around with an animation?


I have been looking for a while on how to move a certain square around on a canvas with JavaScript, and haven't found much. I have done one where it removes itself and replaces itself every frame, but I want it to be smoother and animated. This is my code:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
<button onclick="#">Move Up</button>
<script>
canvas = document.getElementById("myCanvas");
  ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(20, 60, 20, 20);
</script>

So far the button does nothing, is there a function I could add that would move the square around? (in this case up)


Solution

  • To make smooth animations, check about the requestAnimationFrame function (https://developer.mozilla.org/fr/docs/Web/API/Window/requestAnimationFrame).

    Here an example with your code:

    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    
    var squareY = 60;
    var isButtonPressed = false;
    
    ctx.fillStyle = '#FF0000';
    ctx.fillRect(20, squareY, 20, 20);
    
    function moveUp() {
      window.requestAnimationFrame(moveUp);
    
      if (isButtonPressed) {
        squareY -= 10 / 16;
      }
    
      squareY = Math.max(squareY, 5);
    
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = '#FF0000';
      ctx.fillRect(20, squareY, 20, 20);
    }
    
    function onMouseUp() {
      isButtonPressed = false;
    }
    
    function onMouseDown() {
      isButtonPressed = true;
    }
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    
    var squareY = 60;
    var isButtonPressed = false;
    
    ctx.fillStyle = '#FF0000';
    ctx.fillRect(20, squareY, 20, 20);
    
    function moveUp() {
      window.requestAnimationFrame(moveUp);
    
      if (isButtonPressed) {
        squareY -= 10 / 16;
      }
    
      squareY = Math.max(squareY, 5);
    
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = '#FF0000';
      ctx.fillRect(20, squareY, 20, 20);
    }
    
    function onMouseUp() {
      isButtonPressed = false;
    }
    
    function onMouseDown() {
      isButtonPressed = true;
    }
    
    window.addEventListener('keydown', function (e) {
      if (e.key == 'ArrowUp') {
        // if the arrow key is pressed
        squareY -= 10 / 16;
      }
    });
    
    moveUp();
    <canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
    <button onmousedown="onMouseDown()" onmouseup="onMouseUp()">Move Up</button>
    <script>
    </script>