The image is drawn stretched to the HTML canvas when it is created using jQuery

Consider the following code (including 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 a STRETCHED image being displayed rather than the original aspect ratio. Both in Firefox, and in Chrome. Why is this happening? Workarounds?


Update

My apologies that this does not happen if I do not use jQuery to create the canvas element. I will also post this on jQuery forums.

+3
source share
1 answer

HTML5, HTML, - , - HTML-. -, .

jQuery, canvas, 300x300px, CSS width height, -, 300x150. , , , .

, width height canvas. . HTML5 DOCTYPE, img.onload 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>
+8

Source: https://habr.com/ru/post/1753300/


All Articles