Search code examples
javascripthtmlcanvasexportpng

Capture HTML canvas as GIF/JPG/PNG/PDF?


Is it possible to capture or print what's displayed in an HTML canvas as an image or PDF?

I'd like to generate an image via canvas and be able to generate a PNG from that image.


Solution

  • Original answer was specific to a similar question. This has been revised:

    const canvas = document.getElementById('mycanvas')
    const img    = canvas.toDataURL('image/png')
    

    With the value in img you can write it out as a new image like so:

    document.getElementById('existing-image-id').src = img
    

    or

    document.write('<img src="'+img+'"/>');