简体   繁体   中英

How to convert a div into an image, without using html2canvas?

I have a div with a bunch of elements that are transformed with CSS. This div needs to be converted to an image.

I've tried using html2canvas, but it doesn't support Transformed elements very well, so the exported image looks nothing like how the browser displays it. What's the best way to convert a div with styled elements to an image, without using html2canvas?

Styling that doesn't convert well with html2canvas:

transform:  perspective(100px) rotateY(10deg) rotateX(2deg) rotate(-11.5deg);

The html2canvas library is used widely to capture web content directly from the browser. However, it may not be working very well with transformed elements.

As suggested by many, there is no other front end library which is know to be working well in your circumstances. (Did you try this one?)

One other reliable way of doing this is getting the capture done in the server side. You can send the markup to the server, use a headless browser to render and get the image.

Phantom JS is a good candidate for this and is based on Webkit. It is known to work well for most situations.

However, Phantom JS is not actively developed any more. But it maybe of good help in your case.

 var page = require('webpage').create(); page.open('http://www.google.com', function() { setTimeout(function() { page.render('google.png'); phantom.exit(); }, 200); }); 

Using Phantom JS is not an answer here, since it will capturing the whole page, The best way here is domtoimage library to convert a div to an image.

Script

<script src="path/to/dom-to-image.min.js" />
<script>
var node = document.getElementById('my-node');

domtoimage.toPng(node)
.then(function (dataUrl) {
    var img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
})
.catch(function (error) {
    console.error('oops, something went wrong!', error);
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM