javascript drawimage高度不正确

时间:2016-11-17 08:51:43

标签: javascript jquery html drawimage

我有这个图像Image Link,我想将该图像放入画布 但结果的高度和宽度并不准确 这是我的剧本

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.src = "https://s13.postimg.org/rmk2wq6uf/depan.jpg";
ctx.drawImage(img, 0, 0);

jsfiddle link 请帮忙

2 个答案:

答案 0 :(得分:0)

您可以使用canvasnaturalWidth以编程方式设置naturalHeight的高度和宽度:

https://jsfiddle.net/ryanpcmcquen/wbxnkuq4/

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
img.src = "https://s13.postimg.org/rmk2wq6uf/depan.jpg";
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
<canvas id="canvas"></canvas>

MDN: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement

答案 1 :(得分:0)

ctx.drawImage(img, 0, 0, img.width,    img.height,
                   0, 0, canvas.width, canvas.height);

https://jsfiddle.net/Im_Saajan/ekw9n3et/2/

检查这个jsfiddle