HTML5 Canvas distorted

HTML5 Canvas distortion occurs when the canvas element's CSS dimensions don't match its internal drawing dimensions. This creates scaling issues that make drawings appear stretched or blurry.

Understanding Canvas Dimensions

Canvas has two sets of dimensions:

  • Drawing dimensions: Set via width and height attributes
  • Display dimensions: Set via CSS width and height properties

When these don't match, the browser scales the drawing surface to fit the display size, causing distortion.

Default Canvas Size

The default canvas dimensions are:

width = 300px
height = 150px

This gives a 2:1 aspect ratio. If you don't specify dimensions, the canvas uses these defaults.

Correct Way to Set Canvas Size

Always set dimensions using HTML attributes, not CSS:

<!DOCTYPE html>
<html>
<head>
    <style>
        #canvas1 { border: 1px solid red; }
    </style>
</head>
<body>
    <canvas id="canvas1" width="400" height="300"></canvas>
    
    <script>
        const canvas = document.getElementById('canvas1');
        const ctx = canvas.getContext('2d');
        
        // Draw a circle to test distortion
        ctx.beginPath();
        ctx.arc(200, 150, 50, 0, 2 * Math.PI);
        ctx.fillStyle = 'blue';
        ctx.fill();
        ctx.stroke();
    </script>
</body>
</html>

Common Distortion Issues

Problem Cause Solution
Blurry drawings CSS scaling Match HTML and CSS dimensions
Stretched shapes Aspect ratio mismatch Use consistent width/height ratios
Pixelated graphics Small drawing surface Increase canvas width/height attributes

Setting Canvas Size Programmatically

<!DOCTYPE html>
<html>
<body>
    <canvas id="mycanvas"></canvas>
    
    <script>
        const canvas = document.getElementById('mycanvas');
        
        // Set both drawing and display dimensions
        canvas.width = 400;
        canvas.height = 300;
        canvas.style.width = '400px';
        canvas.style.height = '300px';
        canvas.style.border = '1px solid red';
        
        const ctx = canvas.getContext('2d');
        ctx.fillRect(50, 50, 100, 100);
        console.log('Canvas dimensions set programmatically');
    </script>
</body>
</html>

Conclusion

To avoid canvas distortion, always set dimensions using HTML attributes rather than CSS. Ensure drawing dimensions match display dimensions for crisp, undistorted graphics.

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

748 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements