HTML5 canvas drawImage wrong image size

Hello, I have a problem. I am trying to draw an image on canvas using the drawImage function drawImage x 50px on canvas 50px x 50px, but I get less than what I need.

 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function() { $("canvas").css("width", 50); $("canvas").css("height", 50); ctx.drawImage(img, 0, 0, 50, 50); //bad here why not drawing 50x50px image on the canvas? } img.src = 'http://www.w3schools.com/tags/planets.gif'; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <img src="http://www.w3schools.com/tags/planets.gif" width="100" height="100" style="position: absolute; top: 0px; left: 0px"> <canvas id="canvas" style="position: absolute; top: 0px; left: 120px; border: 1px solid #000"></canvas> 
+5
source share
1 answer

Do not set the width and height of the canvas through CSS. This stretches / compresses the actual canvas, scaling the contents.

Use those old HTML width and height attributes:

 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function() { ctx.drawImage(img, 0, 0, 50, 50); } img.src = 'http://www.w3schools.com/tags/planets.gif'; 
 <img src="http://www.w3schools.com/tags/planets.gif" width="100" height="100" style="position: absolute; top: 0px; left: 0px"> <canvas id="canvas" style="position: absolute; top: 0px; left: 120px; border: 1px solid #000" width="50" height="50"> </canvas> 

These attributes actually change the width and height of the contents of the canvas, resulting in an image that exactly matches the size that you expect.

+12
source

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


All Articles