To enable the download of an image from an HTML canvas element, the following steps are typically performed using JavaScript:
- Retrieve the Canvas Element: Obtain a reference to the HTML
<canvas>element from which the image will be downloaded.
- Convert Canvas to Data URL: Use the
toDataURL()method of the canvas element to convert its current content into a data URL. This data URL represents the image in a base64-encoded format. ThetoDataURL()method can accept arguments for image format (e.g.,'image/png','image/jpeg') and quality (for JPEG/WebP).
- Create a Download Link: Dynamically create an anchor (
<a>) element in the DOM. This element will act as the download link.
- Set Link Attributes: Configure the
hrefanddownloadattributes of the newly created anchor element.- The
hrefattribute is set to theimageDataURLobtained in the previous step. - The
downloadattribute is set to the desired filename for the downloaded image. This attribute triggers the download behavior when the link is clicked.
- The
沒有留言:
張貼留言