JSFiddle - React, Tailwind, and code Playground
HTML
<div id="one">
<canvas id="myCanvas" width="578" height="400"></canvas>
</div>
CSS
body {
margin: 0px;
padding: 0px;
}
#one {
background-color:blue;
width:200px;
height:400px;
}
#myCanvas {position:relative;}
JavaScript
var canvas = document.getElementById('myCanvas');
var container = document.getElementById('one');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
imageObj.onload = function() {
var size = fetchSize(imageObj.width,
imageObj.height,
container.offsetWidth,
container.offsetHeight);
canvas.width=size[0];
canvas.height=size[1];
context.drawImage(imageObj, 0, 0, size[0], size[1]);
};
function fetchSize(w,h,max_w,max_h){
var size = [w,h];
var r;
if(w > max_w){
r = max_w / w;
size[0] = max_w;
size[1] = h * r;
h = h * r;
w = w * r;
}
if(h > max_h){
r = max_h / h;
size[1] = max_h;
size[0] = w * r;
}
return size;
}