Question

No matter what I try, I can't figure out why does drawImage vertically stretch a picture. Here is the code:

<canvas id="canvas" style="padding:0;border:0;margin:0 auto;
width:320px;height:456px;z-index:0;"></canvas>

<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var d = new Image
d.src = './images/portadilla.jpg';
d.onload = function a(){context.drawImage(d, 0, 0);}
</script>

My image is 456px high and 320px wide, same as the canvas. I've tried using different images and formats, but the problem remains. How would you solve this?

Was it helpful?

Solution

Because you're not setting the size of the canvas correctly. Don't use CSS/style to set the size but use its attributes:

<canvas id="canvas" width=320 height=456 style="..."></canvas>

Your image is stretched because the default size of the bitmap for a canvas element is 300x150 pixels so if you don't set the size properly the canvas bitmap will be stretched to fit the element size set with CSS.

You can also set the size using JavaScript:

var canvas = document.getElementById('canvas');
canvas.width = 320;
canvas.height = 456;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top