Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html5 canvas drawImage stretched

I tried to draw image on html5 canvas . The issue is image stretched in canvas

load('img_the_scream',
    'http://www.w3schools.com/tags/img_the_scream.jpg',
    function( img ){
        console.log(  img.width , img.height );
        ctx.drawImage( img, 10, 10 , img.width , img.height );
    }
);

I added this issue in http://jsfiddle.net/75rAU/

like image 877
rab Avatar asked May 11 '13 17:05

rab


People also ask

Is HTML5 Canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.

How do I change the size of my canvas in HTML?

Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .

How fast is HTML5 Canvas?

The Canvas tab loaded in one second and takes up 30MB. It also takes up 13% of CPU time all of the time, regardless of whether or not one is looking at it. Video on the HTML page, while I am not moving objects, is actually perfectly smooth.


2 Answers

That is because you modified the canvas size in CSS. The canvas has two separate size : The HTML size (the one you put inside the canvas tag) and the css size, which is actually a rescaling of the canvas. The HTML size is the size you control (when you draw, it uses this size) and the CSS size is the displayed size which is a rescaling of the HTML size.

So here, your canvas has the default size (which I don't remember) but is resized (and stretched) by the css

HTML :

<canvas id="cv" width="350" height="350"></canvas>

CSS :

 #cv {
    background:#ff0;
}

Here I updated your fiddle with the correct size assignation

like image 131
nialna2 Avatar answered Sep 21 '22 12:09

nialna2


Canvas has it's own sizes. 300x150 at default. Styles (width/height) just stretch canvas like any image. So, you should strongly set sizes to what you want. You may do it through html <canvas width="123" height="123"></canvas> or from JS code canvas.width = canvas.height = 123. Also, here you may set sizes by image properties canvas.width = img.width etc.

So, look at jsfiddle: http://jsfiddle.net/75rAU/3/ It works well

Little upd: http://jsfiddle.net/75rAU/4/ — this may help too

like image 33
Novelist Avatar answered Sep 21 '22 12:09

Novelist