简体   繁体   English

如何在不使用 html2canvas 的情况下将 div 转换为图像?

[英]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.我有一个 div,里面有一堆用 CSS 转换的元素。 This div needs to be converted to an image.此 div 需要转换为图像。

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.我尝试过使用 html2canvas,但它不能很好地支持 Transformed 元素,因此导出的图像看起来与浏览器显示它的方式完全不同。 What's the best way to convert a div with styled elements to an image, without using html2canvas?在不使用 html2canvas 的情况下,将带有样式元素的 div 转换为图像的最佳方法是什么?

Styling that doesn't convert well with html2canvas:使用 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. html2canvas库被广泛用于直接从浏览器捕获Web内容。 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. Phantom JS基于Webkit是一个很好的选择。 It is known to work well for most situations. 众所周知,它在大多数情况下都能很好地工作。

However, Phantom JS is not actively developed any more. 但是,Phantom JS不再积极开发。 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.在这里使用Phantom JS不是一个答案,因为它会捕获整个页面,这里最好的方法是domtoimage库将 div 转换为图像。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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