Consider the following code (includes jQuery):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src = "js/jquery-1.4.2.js"></script>
<script type="text/javascript">
jQuery(window).bind("load", function() {
var elem = $("<canvas>", {width:300, height:300});
var canvele = elem[0];
var imm = new Image();
imm.src = "card1/mask-x-6.png";
imm.onload = function(){
var ctx = canvele.getContext('2d');
ctx.drawImage(imm, 0,0);
$('body').append(elem);
}
});
</script>
</head>
<body>
</body>
</html>
This will result in the Image STRETCHED, not in it original aspect ratio. Both on firefox and Chrome. Why this happens? Workarounds?
Update
My apologies this thing doesn’t happen if I don’t use jQuery to generate the canvas Element. I’ll post this to jQuery forums too.
An HTML5 Canvas, like an HTML image, has both an intrinsic size—the number of pixels wide and tall in the source image—and a display size—how large it is drawn on the HTML page. If these two sizes are set differently, the image will be stretched.
The jQuery code you have used to create your canvas element sets the display size to 300x300px by setting the CSS
widthandheightattributes, but does not set the intrinsic size differently than the default of 300×150. As such, anything you draw will be stretched twice as tall.To fix it, set the actual
widthandheightattributes of the canvas element directly. In the following code I’ve made this fix. I’ve also fixed it to use an HTML5 DOCTYPE, and I set theimg.onloadbefore theimg.src: