Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  161] [ 2]  / answers: 1 / hits: 6327  / 9 Years ago, wed, march 18, 2015, 12:00:00

Hello i have problem i try to drawing image on the canvas with drawImage function 50px x 50px on the 50px x 50px canvas, but i get smaller than 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>




More From » html

 Answers
4

Don't set a canvas's width and height through CSS. This will stretch / compress the actual canvas, scaling the contents.



Use those old HTML width and height attributes instead:





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 canvas's context's width and height, resulting in a image that's exactly the size you expect it to be.


[#38529] Tuesday, March 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;