Drawing image on canvas - larger than real

latata picture latata · Apr 3, 2013 · Viewed 16.4k times · Source

I want to draw an image from jpg file on canvas. My code:

var canvas = document.getElementById('my_canvas');
  var ctx = canvas.getContext('2d');
  var imageObj = new Image();

  imageObj.onload = function() {
    ctx.drawImage(imageObj, 0, 0);
  };
  imageObj.src = 'img/my_image.jpg';

The problem is that the image on canvas is much bigger than in file. Why? How can I draw image real size?

UPDATE: result: http://jsfiddle.net/AJK2t/

Answer

Phrogz picture Phrogz · Apr 3, 2013

This is your problem:

<canvas style="width: 700px; height: 400px;" id="konf"></canvas>

You are setting the visual size of your canvas, but not the number of pixels. Consequently the browser is scaling the canvas pixels up.

The simplest fix is:

<canvas width="700" height="400" id="konf"></canvas>

The width and height parameters control the number of pixels in the canvas. With no CSS styling, the default visual size of the canvas will also be this size, resulting in one canvas pixel per screen pixel (assuming you have not zoomed the web browser).

Copy/pasting from my answer to a related question:

Think about what happens if you have a JPG that is 32x32 (it has exactly 1024 total pixels) but specify via CSS that it should appear as width:800px; height:16px. The same thing applies to HTML Canvas:

  • The width and height attributes of the canvas element itself decide how many pixels you can draw on. If you don't specify the height and width of the canvas element, then per the specs:
    "the width attribute defaults to 300, and the height attribute defaults to 150."

  • The width and height CSS properties control the size that the element displays on screen. If the CSS dimensions are not set, the intrinsic size of the element is used for layout.

If you specify in CSS a different size than the actual dimensions of the canvas it must be stretched and squashed by the browser as necessary for display. You can see an example of this here: http://jsfiddle.net/9bheb/5/