Renandatta Rooziq Renandatta Rooziq - 18 days ago 5
HTML Question

javascript drawimage height incorrect

i have this image Image Link and i want to put that image into canvas
but the result height and width did not accurate
this is my script

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
please help

Answer

You can set the height and width of the canvas programmatically using naturalWidth and 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

Comments