javascript Html5 画布 drawImage 拉伸
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16499687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html5 canvas drawImage stretched
提问by rab
I tried to draw image on html5 canvas . The issue is image stretched in canvas
我试图在 html5 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/添加了这个问题
回答by Malharhak
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.
那是因为您在 CSS 中修改了画布大小。画布有两个独立的大小:HTML 大小(您放在 canvas 标签中的那个大小)和 css 大小,它实际上是画布的重新缩放。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 fiddlewith the correct size assignation
在这里,我用正确的大小分配更新了你的小提琴
回答by Novelist
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.
Canvas 有它自己的尺寸。300x150
默认情况下。样式(宽度/高度)canvas
就像任何图像一样伸展。所以,你应该强烈地将尺寸设置为你想要的。您可以通过 html<canvas width="123" height="123"></canvas>
或 JS 代码来完成canvas.width = canvas.height = 123
。此外,在这里您可以通过图像属性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/——这也可能有帮助