Reputation: 455
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>
Upvotes: 9
Views: 6922
Reputation: 72857
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.
Upvotes: 20