JSFiddle - React, Tailwind, and code Playground

by Subhasish2015

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<img src="http://p1.pichost.me/i/25/1483610.jpg" id="img" style="display:none;">
    <canvas id="hidden1"></canvas>
    <canvas id="fabric"></canvas>

JavaScript

var canvas = document.getElementById("hidden1");
var img = document.getElementById("img");
canvas.height = img.height;
canvas.width = img.width;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0,0);


//now I am hiding the canvas and generating image using fabric js on a 500*500 canvas.
var height = img.height;
var width = img.width;
//canvas.style.display = 'none';
var fcanvas = document.getElementById("fabric");
//maintaining aspect ratio
fcanvas.width= $(window).width()*0.78;
fcanvas.height = $(window).height()*0.78;
		
		var imageAspectRatio = width / height;
		var canvasAspectRatio = fcanvas.width / fcanvas.height;
		var renderableHeight, renderableWidth, xStart, yStart;

		// If image's aspect ratio is less than canvas's we fit on height
		// and place the image centrally along width
		if(imageAspectRatio < canvasAspectRatio) {
			renderableHeight = fcanvas.height;
			renderableWidth = width * (renderableHeight / height);
			xStart = (fcanvas.width - renderableWidth) / 2;
			yStart = 0;
		}

		// If image's aspect ratio is greater than canvas's we fit on width
		// and place the image centrally along height
		else if(imageAspectRatio > canvasAspectRatio) {
			renderableWidth = fcanvas.width
			renderableHeight = height * (renderableWidth / width);
			xStart = 0;
			yStart = (fcanvas.height - renderableHeight) / 2;
		}

		// Happy path - keep aspect ratio
		else {
			renderableHeight = fcanvas.height;
			renderableWidth = fcanvas.width;
			xStart = 0;
			yStart = 0;
		}
		
		
	    fcanvas.width= renderableWidth;
		fcanvas.height = renderableHeight;
        var fabricCanvas= new fabric.Canvas("fabric");
fabric.Image.fromURL(canvas.toDataURL(), function(img) {
});