Drawing image on canvas - larger than real Drawing image on canvas - larger than real javascript javascript

Drawing image on canvas - larger than real


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/


Working Example: http://jsfiddle.net/jzF5R/

In order to scale an image you need to provide the scaled width and height you want to ctx.drawImage():

// x, y, width, heightctx.drawImage(imageObj, 0, 0, 100, 50);

Maintain original image size:

ctx.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height);

Keep canvas from overflowing off the page:

ctx.canvas.width = document.body.clientWidth;

You can easily scale the image width and height to 70% of original:

ctx.drawImage(imageObj, 0, 0, imageObj.width * 0.7, imageObj.height * 0.7);


To display a MJPEG stream on a canvas (or something else) without define the width and the height of the canvas in HTML, so only using CSS to get a responsive canvas and fit with the page, I use that:

//get size from CSSvar sizeWidth = context.canvas.clientWidth;   var sizeHeight = context.canvas.clientHeight;   //here the solution, it replaces HTML width="" height=""canvas.width = sizeWidth;canvas.height = sizeHeight;...........context.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height, 0, 0, sizeWidth, sizeHeight);

The picture is entirely contained in the canvas whatever the size of the canvas (the rate between height and width is not kept but it doesn't matter, an height:auto; in css can fix that).

Et voilĂ  !