javascript drawimage 高度不正确

javascript drawimage height incorrect

我有这张图片 Image Link 我想把这张图片放到 canvas 但结果高度和宽度不准确 这是我的脚本

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 请帮忙

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

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

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

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

检查这个 jsfiddle