Earlier I wrote about taking a screenshot of an element with JavaScript, SVG and canvas, and how the experience on an iOS PWA was poor. I decided putting the final image in a popover with a share button would be better than that, but there are performance issues to fix first.
Originally the image was generated on page load in the background. Looking in the dev tools performance panel the canvas.toDataURL()
method is a long task, taking 170ms.
[IMAGE]
So, that’s the task at hand: get rid of the long task warning.
First thing I tried was the canvas.toBlob()
method. That got it down to 77ms. Not bad, but still a long task according to dev tools.
[IMAGE]
canvas.toBlob(blob => { const newImage = document.createElement(‘img’); const url = URL.createObjectURL(blob);
newImage.addEventListener('load', () => {
newImage.width = newImage.naturalWidth;
newImage.height = newImage.naturalHeight;
// Clean up
URL.revokeObjectURL(url);
});
newImage.src = url;
screenshot.href = newImage.src;
document.body.appendChild(newImage);
}, ‘image/jpeg’, ‘1.0’);