Using the dom-to-image library we can convert an image using Promises.
Usage example, conversion from DOM object to PNG image:
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);
});
Behind the scenes, the toPng method is chain of a Promise object:
/**
* @param {Node} node - The DOM Node object to render
* @param {Object} options - Rendering options, @see {@link toSvg}
* @return {Promise} - A promise that is fulfilled with a PNG image data URL
* */
function toPng(node, options) {
return draw(node, options || {})
.then(function (canvas) {
return canvas.toDataURL();
});
}
I want to convert images based on a Node array, and then, to get that images in order. The problem is when I call toPng()
the async process time varies in function of the DOM target complexity. So it will return before the pages with less complexity, instead of return the pages in order.
let pages = document.querySelectorAll('.page');
pages.forEach(page => {
let dataUrl = convertToPng(page.firstElementChild);
});
function convertToPng(page) {
domtoimage.toPng(page)
.then(function (dataUrl) {
console.log(page); // prints pages randomly (e.g. page3, page1, page2)
})
}
A possible solution would be use a Promise.all()
method and attach with a forEach()
method all the Promises. But in this case, that I'm using an external library, I don't know how to approach in order to get first the page1, then the page 2, and so on...