简体   繁体   English

Html5画布drawImage拉伸

[英]Html5 canvas drawImage stretched

I tried to draw image on html5 canvas . 我试图在html5画布上绘制图像。 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/ 我在http://jsfiddle.net/75rAU/中添加了这个问题

That is because you modified the canvas size in CSS. 那是因为你在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. 画布有两个独立的大小:HTML大小(放在canvas标签内的大小)和css大小,实际上是画布的重新缩放。 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. HTML大小是您控制的大小(绘制时,它使用此大小),CSS大小是显示的大小,它是HTML大小的重新缩放。

So here, your canvas has the default size (which I don't remember) but is resized (and stretched) by the css 所以在这里,你的画布有默认大小(我不记得了)但是由css调整大小(和拉伸)

HTML : HTML:

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

CSS : CSS:

 #cv {
    background:#ff0;
}

Here I updated your fiddle with the correct size assignation 在这里,我用正确的大小分配更新你的小提琴

Canvas has it's own sizes. Canvas有自己的尺寸。 300x150 at default. 默认为300x150 Styles (width/height) just stretch canvas like any image. 样式(宽度/高度)就像任何图像一样拉伸canvas 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 . 您可以通过html <canvas width="123" height="123"></canvas>或JS代码canvas.width = canvas.height = 123 Also, here you may set sizes by image properties canvas.width = img.width etc. 此外,您可以在此处按图像属性canvas.width = img.width等设置大小。

So, look at jsfiddle: http://jsfiddle.net/75rAU/3/ It works well 那么,看看jsfiddle: http//jsfiddle.net/75rAU/3/它运作良好

Little upd : http://jsfiddle.net/75rAU/4/ — this may help too 更新http//jsfiddle.net/75rAU/4/ - 这也可能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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