How to draw an oval in HTML5 canvas?

Drawing an oval in HTML5 canvas can be achieved by scaling a circle. Since canvas doesn't have a built-in oval method, we use the scale() transformation to stretch a circle into an elliptical shape.

How It Works

The technique involves three steps:

  • Save the current canvas state with save()
  • Apply scaling transformation to stretch the circle
  • Draw a circle using arc(), which appears as an oval due to scaling
  • Restore the original state with restore()

Example

<!DOCTYPE HTML>
<html>
<head>
    <title>HTML5 Canvas Oval</title>
</head>
<body>
    <canvas id="newCanvas" width="450" height="300" style="border: 1px solid #ccc;"></canvas>
    <script>
        // Get canvas and context
        var canvas = document.getElementById('newCanvas');
        var context = canvas.getContext('2d');
        
        // Oval parameters
        var centerX = 0;
        var centerY = 0;
        var radius = 40;
        
        // Save current state
        context.save();
        
        // Move to center of canvas
        context.translate(canvas.width / 2, canvas.height / 2);
        
        // Scale horizontally by 2, vertically by 1 (creates oval)
        context.scale(2, 1);
        
        // Draw circle (will appear as oval due to scaling)
        context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
        
        // Restore original state before styling
        context.restore();
        
        // Apply fill and stroke
        context.fillStyle = '#000000';
        context.fill();
        context.lineWidth = 2;
        context.strokeStyle = 'yellow';
        context.stroke();
    </script>
</body>
</html>

Output

Key Parameters

  • scale(2, 1): Stretches horizontally by factor of 2, keeps vertical scale at 1
  • translate(): Positions the oval at canvas center
  • save()/restore(): Preserves canvas state to prevent scaling from affecting stroke width

Alternative Scaling

You can create different oval shapes by adjusting the scale values:

// Tall oval (vertical stretch)
context.scale(1, 2);

// Wide oval (horizontal stretch)  
context.scale(3, 1);

// Slightly stretched oval
context.scale(1.5, 0.8);

Conclusion

HTML5 canvas ovals are created by scaling circles using the scale() transformation. Always use save() and restore() to isolate the scaling transformation and maintain proper stroke appearance.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements