3

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.

Phrogz
  • 271,922
  • 98
  • 616
  • 693
gotch4
  • 12,473
  • 27
  • 100
  • 161

1 Answers1

8

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 width and height attributes, but does not set the intrinsic size differently than the default of 300x150. As such, anything you draw will be stretched twice as tall.

To fix it, set the actual width and height attributes 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 the img.onload before the img.src:

<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Setting Canvas Dimensions</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js">
</script>
<script type="text/javascript">
$(function(){
  var elem = $("<canvas>", {width:300, height:300});
  var canvele = elem[0];
  canvele.width = canvele.height = 300;

  var imm = new Image;
  imm.onload = function(){
    var ctx = canvele.getContext('2d');
    ctx.drawImage(imm, 0,0);
    $('body').append(elem);
  };
  imm.src = "http://phrogz.net/tmp/gkhead.jpg";
});
</script>
</head><body></body></html>
Community
  • 1
  • 1
Phrogz
  • 271,922
  • 98
  • 616
  • 693