Html2canvas Ignores object-fit for image
Asked Answered
C

1

6

I've been trying to make use of html2canvas to take a screenshot of a element

I noticed an image inside the div element that uses the object-fit property becomes stretched after the html2canvas screenshot

Is there a walk around for this. Here is my code

<script>window.addEventListener('load', function () {

      
 var bigCanvas = $("<div>").appendTo('body');
 var scaledElement = $("#Element").clone()
 .css({
  'transform': 'scale(1,1)',
  'transform-origin': '0 0'
 })
 .appendTo(bigCanvas);
 
 var oldWidth = scaledElement.width();
 var oldHeight = scaledElement.height();

 var newWidth = oldWidth * 1;
 var newHeight = oldHeight * 1;
 
 bigCanvas.css({
   'width': newWidth,
   'height': newHeight
 })


 html2canvas(bigCanvas, {
   onrendered: function(canvasq) {
   var image = document.getElementById('image');
  image.style.width='300px';
 
   image.src = canvasq.toDataURL();
   
    bigCanvas.remove() ;
   }
 });}) </script>

While html goes as

<div id="Element" class="container">
  
<div class="bg-light p-3 text-center">

<h3>iPhone 12 Pro Max</h3>

<div class="m-2 shadow" style="height:400px;width:100%;">

<img src="img/agency.jpeg" style="object-fit:cover;height:100%;width:100%;" />
</div>

<h4>Now available for free</h4>

</div>

</div>

<div class="container" style="width:100%;border:2px solid black;overflow:hidden">

 <img src="" id="image" style="max-width:100%;"/>
 </div>
Claudclauddetta answered 26/1, 2021 at 3:27 Comment(1)
I solved this issue by creating a div with a background-image. html2canvas supports background-size.Psycho
A
5

I had the same issue, unfortunally it seems that html2cavas doesn't support the object-fit property but i resolve with flexbox and the result it's good, it's important to set the width and height for parent node:

 .logo-preview-inner {
      height: 200px;
      width: 200px;
      border-radius: 50%;
      border: solid 1px #e6e6e6;
      margin: 0 auto;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      img {
        width: 100%;
      }

where the class .logo-preview-inner is the parent node and the image is the child i hope to help you!

Applaud answered 25/5, 2021 at 10:53 Comment(1)
The code you posted is not CSS, and also wouldn't really solve the issue, just cram the image into the already defined size. But yes, you are right, it's not supported.Callas

© 2022 - 2024 — McMap. All rights reserved.