Home > Web Front-end > JS Tutorial > How Can I Save an HTML Canvas as a PNG Image?

How Can I Save an HTML Canvas as a PNG Image?

DDD
Release: 2024-12-26 04:41:17
Original
535 people have browsed it

How Can I Save an HTML Canvas as a PNG Image?

Capturing HTML Canvas Output as Various Image Formats

Question:

Can an HTML canvas's content be captured or printed as an image or PDF? Specifically, how can an image be generated from a canvas and saved as a PNG?

Answer:

Using HTML5's advanced features, capturing and saving canvas output as an image has become a straightforward process:

const canvas = document.getElementById('mycanvas');
const img = canvas.toDataURL('image/png');
Copy after login

Once the desired image data is stored in the img variable, it can be used in various ways:

  • Generate a new image:
document.getElementById('existing-image-id').src = img;
Copy after login
  • Display directly in HTML:
document.write('<img src="' + img + '" />');
Copy after login

This script enables you to capture and save your canvas output as a PNG image, providing convenient methods for further use or distribution.

The above is the detailed content of How Can I Save an HTML Canvas as a PNG Image?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template