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.
source share