JSFiddle - React, Tailwind, and code Playground
by al3x88
HTML
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<img id="image" src="https://static.fjcdn.com/large/pictures/03/b1/03b120_799520.jpg" style="display:none">
<canvas id="c" width="400" height="400"></canvas>
JavaScript
var c = document.getElementById("c");
var ctx = c.getContext("2d");
var img = document.getElementById("image");
var widthPer = 400; // Desire width to draw in pixel as per original image size.
var heightPer = 400; // Desire height to draw in pixel as per original image size.
var drawImgWidth = (img.width/img.naturalWidth)*widthPer; // calculated width in pixel.
var drawImgHeight = (img.height/img.naturalHeight)*heightPer; // calculated height in pixel.
if(img.width != img.naturalWidth) {
ctx.drawImage(img, 0, 0, drawImgWidth, drawImgHeight, 0, 0, 400, 400);
}
else {
ctx.drawImage(img, 0, 0, widthPer, heightPer, 0, 0, 400, 400);
}