2025年9月5日 星期五

[HTML] [JS] HTML Canvas Download Image

  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.
JavaScript
    const canvas = document.getElementById('myCanvas');
  • 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. The toDataURL() method can accept arguments for image format (e.g., 'image/png''image/jpeg') and quality (for JPEG/WebP).
JavaScript
    const imageDataURL = canvas.toDataURL('image/png'); // Or 'image/jpeg', 'image/webp'
  • Create a Download Link: Dynamically create an anchor (<a>) element in the DOM. This element will act as the download link.
JavaScript
    const downloadLink = document.createElement('a');
  • Set Link Attributes: Configure the href and download attributes of the newly created anchor element.
    • The href attribute is set to the imageDataURL obtained in the previous step.
    • The download attribute is set to the desired filename for the downloaded image. This attribute triggers the download behavior when the link is clicked.
JavaScript
    downloadLink.href = imageDataURL;    downloadLink.download = 'my_canvas_image.png'; // Specify desired filename and extension

沒有留言:

張貼留言

辦公室心態秘技輯錄

要過感恩的生活,在工作中也要如是。 有同事脾氣暴躁,所以跟他相處不刺激到他已值得感恩了,可是當他發脾氣的時候,告訴自已不要放於心裏,不要被他的說話影響自己就好了。 有同事不負責任,這個很難相處,就做好自己本份,辛苦委屈唯有交托給主。 有同事懶懶閒,這也改變不到他的心態,不與他說話...