Background image captures in half after using DomToImage

So I’m trying out Dom-to-Image but ran into a deadend. I have this div with a fixed width and height of 700px and 500px respectively. This is the div which I want to take a screenshot of with Dom-to-Image plugin.

When the div is left-aligned on the viewport, the screen capture is perfect and I can download the image. But if I make the div center with margin: 0 auto;, then I get one-third of the screenshot and not the full image.

Here’s the issue when it is centered:

enter image description here

What I want:

No matter where my div is placed, I only want to take the screenshot of that full div. How can I do that?

Here’s the code:

$(document).ready(() => {
    const imgDiv                    = document.querySelector('#div');
    const downloadBtn               = document.querySelector('#download');


   $(downloadBtn).click(() => {
          domtoimage.toBlob(imgDiv).then( blob => {
                saveAs(blob, 'myImage.png');
          });
   });
   
   
});
#div {
    width: 700px;
    height: 500px;
    background-image: url('https://img.glyphs.co/img?q=85&w=900&src=aHR0cHM6Ly9zMy5tZWRpYWxvb3QuY29tL3Jlc291cmNlcy9HZW9tZXRyaWMtQmFja2dyb3VuZC1QYXR0ZXJucy1QcmV2aWV3LTJiLmpwZw==');
    background-position: center center;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
}


.text-block {
    display: flex;
    flex-direction: column;
    z-index: 9999;
}

.text,
.name {
    color: #fff;
    text-align: center;
    margin: 0;
}

.text {
    padding: 0 40px;
    margin-bottom: 20px;
    font-size: 15px;
}

.name {
    font-size: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="div">
     <div class="text-block">
          <p class="text">Booooooooooooooossss </p>
          <p class="name">s</p>
     </div>
</div>

<button id="download">Download</button>

9 thoughts on “Background image captures in half after using DomToImage”

Leave a Comment