askvity

How to Move a Circle in HTML Canvas?

Published in Canvas Animation 4 mins read

To move a circle in HTML Canvas, you don't literally move it like an element in the DOM. Instead, you achieve the illusion of movement by repeatedly clearing the canvas and redrawing the circle at updated coordinates.

The Core Concept: Redrawing for Movement

HTML Canvas drawing is immediate; once a shape is drawn, it becomes part of the pixel data on the canvas. To make something appear to move, you must:

  1. Clear the previous drawing from the canvas.
  2. Update the coordinates (x and y) where you want the circle to be next.
  3. Redraw the circle at the new coordinates.
  4. Repeat this process rapidly, typically using an animation loop (like requestAnimationFrame), to create smooth animation.

Using JavaScript Coordinates (x, y)

The core drawing functions for circles in the HTML Canvas 2D context, such as arc() or ellipse(), require you to specify the center point using x and y coordinates.

As highlighted in the reference, functions like ellipse (or commonly, arc for circles) use x and y as the parameter. You can play around with both of this parameter to change its location while redrawing.

Here's a simplified breakdown of the steps involved in JavaScript:

  1. Get Canvas Context: Obtain the 2D rendering context for your canvas element.

    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
  2. Define Circle Properties: Store the circle's current position (x, y), radius, and perhaps color.

    let circleX = 50; // Initial X coordinate
    let circleY = 75; // Initial Y coordinate
    const circleRadius = 20;
    const circleColor = 'blue';
    const moveSpeed = 2; // Pixels per frame
  3. Create Drawing Function: A function to draw the circle at the current circleX, circleY.

    function drawCircle() {
      ctx.beginPath();
      // arc(x, y, radius, startAngle, endAngle, counterclockwise)
      ctx.arc(circleX, circleY, circleRadius, 0, Math.PI * 2, false);
      ctx.fillStyle = circleColor;
      ctx.fill();
      ctx.closePath();
    }
  4. Create Clearing Function: A function to clear the entire canvas.

    function clearCanvas() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
  5. Create Update Logic: A function to change circleX and circleY based on desired movement. This is where you "play around" with the parameters.

    function updatePosition() {
      // Example: Move the circle to the right
      circleX += moveSpeed;
    
      // Example: Bounce off the right edge
      if (circleX + circleRadius > canvas.width) {
        circleX = canvas.width - circleRadius; // Prevent going off screen
        // To make it bounce, you'd reverse the speed: moveSpeed = -moveSpeed;
      }
    }
  6. Implement Animation Loop: Use requestAnimationFrame to repeatedly clear, update, and redraw.

    function animate() {
      clearCanvas();      // Clear the frame
      updatePosition();   // Update coordinates
      drawCircle();       // Draw at new coordinates
    
      requestAnimationFrame(animate); // Loop
    }
    
    // Start the animation
    animate();

By implementing these steps, you can make the circle appear to move smoothly across the canvas.

Key Parameters Explained

Parameter Description Role in Movement
x The x-coordinate of the circle's center. Changed over time to move horizontally.
y The y-coordinate of the circle's center. Changed over time to move vertically.
Redrawing Clearing the canvas and drawing again. Essential for updating the visual state.
Animation Loop Repeatedly executing the clear-update-draw steps. Creates the illusion of smooth motion.

Understanding that canvas drawing is state-based and requires redrawing at new x and y positions is the key to creating animations and moving shapes.

Related Articles