This amazing tool is what I use: DOM to Image library
If you prefer NPM:
npm install dom-to-image
then import,
import domtoimage from 'dom-to-image';
Here's a snippet of HTML with markup that should be saved as an image:
<div id="my-node">
<img src="/assets/images/image.jpg"/>
</div>
<div class="btn-group">
<button class="btn-primary" (click)="convertToPng()">Convert to PNG</button>
<button class="btn-primary" (click)="convertToJpeg()">Convert to JPEG</button>
<button class="btn-primary" (click)="downloadAsPng()">Download as PNG</button>
<button class="btn-primary" (click)="downloadAsJpeg()">Download as JPEG</button>
</div>
CSS filters can also be applied, here's an example:
img {
filter: grayscale(100%);
}
To Convert to PNG:
convertToPng(){
let 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);
});
}
To Convert to JPEG:
convertToJpeg(){
let node = document.getElementById('my-node');
domtoimage.toJpeg(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);
});
}
To Download as PNG:
downloadAsPng(){
let node = document.getElementById('my-node');
domtoimage.toPng(node)
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'my-image-name.png';
link.href = dataUrl;
link.click();
});
}
To Download as JPEG:
downloadAsJpeg(){
let node = document.getElementById('my-node');
domtoimage.toJpeg(node, { quality: 0.95 })
.then(function (dataUrl) {
var link = document.createElement('a');
link.download = 'my-image-name.jpeg';
link.href = dataUrl;
link.click();
});
}