保存 dom/html 为图片
- 可以使用
html2canvas
+ canvas2image
- 或者使用
dom-to-image
- 或者使用
html-to-image
<script src="https://unpkg.com/html2canvas@1.0.0-rc.5/dist/html2canvas.js"></script>
<script src="https://www.jqueryscript.net/demo/Capture-HTML-Elements-Screenshot/canvas2image.js"></script>
<script src="https://unpkg.com/dom-to-image@2.6.0/dist/dom-to-image.min.js">`dom 转图片`</script>
<div id="root">一些文本</div>
const node = document.getElementById(`root`)
{
html2canvas(node).then(function(canvas) {
document.body.appendChild(canvas);
Canvas2Image.saveAsImage(document.querySelector(`canvas`), canvas.width, canvas.height, `png`, `test`)
});
}
{
const scale = 1.5;
domtoimage.toPng(node, {
height: node.offsetHeight * scale,
width: node.offsetWidth * scale,
style: {
transform: "scale(" + scale + ")",
transformOrigin: "top left",
width: node.offsetWidth + "px",
height: node.offsetHeight + "px"
}}).then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'my-image-name.png';
link.href = dataUrl;
link.click();
});
}
{
domtoimage.toBlob(node).then(async function (blob) {
try {
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
console.log('Image copied.');
} catch(err) {
console.error(err.name, err.message);
}
});
}