set width and height of an image after transform: rotate

Hey,

Please Try this code.

var $=jQuery.noConflict();
$(document).ready(function(){
	$('#RotateButton').click(function(){
	   $('.col').toggleClass("afterRot");
	});
});
/* ----- IE Support CSS Script ----- */
var userAgent, ieReg, ie;
userAgent = window.navigator.userAgent;
ieReg = /msie|Trident.*rv[ :]*11\./gi;
ie = ieReg.test(userAgent);
if(ie) {
  $(".col").each(function () {
    var $container = $(this),
        imgUrl = $container.find("img").prop("src");
    if (imgUrl) {
      $container.css("backgroundImage", 'url(' + imgUrl + ')').addClass("custom-object-fit");
    }
  });
}
body { padding: 0; margin: 0; }
.col { position: relative; display: block; width:100vh; height: 100vh; }
.afterRot{ transform: rotate(90deg); object-fit: cover; }
.col img { position: absolute; top: 0; left: 0; right: 0; width: 100%; height: 100%;	object-fit: cover; }
.custom-object-fit { position: relative; background-size: cover; background-position: center center; }
.custom-object-fit img { opacity: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mob">
	<button type="button" id="RotateButton"> Rotate </button>
	<div class="col">     
    	<img class="nor" id="rowImg" src="https://cdn-images-1.medium.com/max/1600/1*tSyuv3ZRCfsSD5aXB7v8DQ.png">
    </div>
</div>


I have figured out an automated way as below:

First, I am getting natural height and width of the image (from onload trigger):

naturalWidth = event.currentTarget.naturalWidth
naturalHeight = event.currentTarget.naturalHeight

Then I am computing a transform scale using aspect-ratio and generating transform style as below (pseudo-code):

For 90deg (y-shift):

  const scale = naturalWidth > naturalHeight ? naturalHeight / naturalWidth : 1
  const yshift = -100 * scale
  const style = "transform:rotate(90deg) translateY("+yshift+"%) scale("+scale+"); transform-origin: top left;"

For 270deg (x-shift):

  const scale = naturalWidth > naturalHeight ? naturalHeight / naturalWidth : 1
  const xshift = -100 * scale
  const style = "transform:rotate(270deg) translateX("+xshift+"%) scale("+scale+"); transform-origin: top left;"

Hope this helps.

Tags:

Html

Css