Search code examples
javascriptimagecanvassave

How can I save the canvas as an image instead of downloading it directly?


I have a p5 game and I want to save the canvas as a p5.Image so I can show it on the canvas later. However I only found the saveCanvas() function which directly downloads an image of the canvas. Is there a way to save it as an image for later use?


Solution

  • AFAIK the p5.js library does not provide a way to do this. However, you can transform it into a data url via this code:

    const dataURL = document.querySelector("#myCanvas")
                            .toDataURL()
                            .replace("image/png", "image/octet-stream");
    

    You can then use this as a regular image source, e.g. you could redirect the current page to the image:

    window.location.href = dataURL;