'How to convert a canvas to a png file?

I want to convert a canvas to a png file and save it in order to do comparison tests with Cypress. The problem is that the file I create is empty.

cy.get('#imgcanv').as('canvas');
cy.get('@canvas').then((cnv) => {
url = cnv[0].toDataURL('image/png');
cy.log(cnv); // OK

const data = url.replace(/^data:image\/png;base64,/, '')
cy.writeFile('first-image.png', data, 'base64');

What is the problem?



Solution 1:[1]

The issue you have here is that cy.writeFile need to run in the node context, not JavaScript.

For that you need to create a task in your plugin file that wraps this call. Then just call the task instead, something like

cy.task('writeFile', {filename, data})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mika