Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid HTML Canvas auto-stretching

I have the following piece of HTML:

<style type="text/css">
    #c{width:200px;height:500px}
</style>
<canvas id="c"></canvas>
<script type="text/javascript">
    var i = new Image();
    i.onload = function () {
        var ctx = document.getElementById('c').getContext('2d');
        ctx.drawImage(i, 0, 0);
    }
    i.width = i.height = 20; // actual size of square.png
    i.src = 'square.png';
</script>

The issue is that the drawn image is automatically stretched (resized) proportionally with the size of the canvas. I have tried using all available parameters (drawImage(i, 0, 0, 20, 20, 0, 0, 20, 20)) and that didn't help.

What is causing my drawing to stretch and how can I prevent that?

Thanks,
Tom

like image 721
Tom Avatar asked May 23 '10 14:05

Tom


2 Answers

You need the width and height attributes in the canvas element. They specify the coordinate space for the canvas. Apparently, it defaults to a canvas of a 2:1 aspect ratio, which your CSS is skewing into a square.

like image 192
Eric Avatar answered Oct 21 '22 07:10

Eric


It's worth noting that the Width and Height attributes of canvas are not like the old school <img> width and height attributes. They are not a substitute for CSS. They specify how many pixels the pixel buffer in the canvas itself should have, and if you don't apply a size to it with css, css will imply it's size from that shape of that pixel buffer. Setting the element's size in css does not set the size of the pixel buffer - it resizes it. From a CSS perspective, a <canvas> is entirely the same thing as an <img>.

like image 40
Blixxy Avatar answered Oct 21 '22 06:10

Blixxy