Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

How to pass HTML to JPG/PNG? In Javascript/Typescript

How can i convert an HTML to a JPG/PNG image? I already tried various options but none works for me, they only make the image of some parts of the HTML.

Example with html2canvas:

TS

capturar() {
    html2canvas(document.body).then(function(canvas) {
      document.body.appendChild(canvas);
    });
}

HTML

<div id="capture">
    <ion-grid class="grid-padding-info-verde">
      <ion-row class="row-info">

        <ion-col size="12">
          <ion-icon name="checkmark-circle" class="check-icono"></ion-icon>
        </ion-col>

        <ion-col size="12" class="info-col">
          <span class="trans-sub"> {{ this.fecha }}</span>
        </ion-col>

      </ion-row>
    </ion-grid>
</div>

This error I get when I use the example: enter image description here

"DOMException: Failed to set the 'adoptedStyleSheets' property on 'ShadowRoot': Sharing constructed stylesheets in multiple documents is not allowed"

Do you know any other tools? Basically I need to take a screenshot of only a part of my screen not the full screen. Any ideas?

question from:https://stackoverflow.com/questions/65886015/how-to-pass-html-to-jpg-png-in-javascript-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the package: https://www.npmjs.com/package/dom-to-image

In your page:

import domtoimage from 'dom-to-image';

capturar(){
    var node = document.getElementById('capture');
    var options = {quality: 1};

    domtoimage.toJpeg(node, options).then((dataUrl) => {
      console.log(dataUrl) //Image in base64 jpeg
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...