JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<canvas id="canvas1" width="600" height="600">Sorry but your browser doesn't support the canvas tag.</canvas>
</div>
<div>
<canvas id="canvas2" width="100" height="300">Sorry but your browser doesn't support the canvas tag.</canvas>
</div>
CSS
div{
height: 100px;
width: 300px;
float: left;
}
JavaScript
var canvas1 = document.getElementById('canvas1');
var context1 = canvas1.getContext('2d')
var canvas2 = document.getElementById('canvas2');
var context2 = canvas2.getContext('2d');
var image1 = new Image();
image1.src = "http://media.giphy.com/media/iNk83OBPzlA8o/giphy.gif";
image1.onload = function () {
context1.fillStyle = "#000";
context1.fillRect(0, 0, canvas1.width, canvas1.height);
context2.fillStyle = "#F00";
context2.fillRect(0, 0, canvas2.width, canvas2.height);
ratio(context1, canvas1, image1);
ratio(context2, canvas2, image1);
}
function ratio(context1, canvas1, image1) {
var imageRatio = image1.width / image1.height;
var newHeight = canvas1.width / imageRatio;
var newWidth = canvas1.height * imageRatio;
var heightDiff = newHeight - canvas1.height;
var widthDiff = newWidth - canvas1.width;
if (widthDiff >= heightDiff) {
context1.drawImage(image1, 0, 0, canvas1.width, canvas1.width / imageRatio);
} else {
context1.drawImage(image1, 0, 0, canvas1.height * imageRatio, canvas1.height);
}
}