简体   繁体   中英

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM