How to save canvas images by button onclick?

by haylee.mertz , in category: Javascript , 5 months ago

How to save canvas images by button onclick?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 5 months ago

@haylee.mertz 

You can save a canvas image by using the toDataURL() method of the canvas element. Here's an example of how you can do this with a button click event:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
    <title>Save Canvas Image</title>
</head>
<body>
    <canvas id="canvas" width="200" height="200"></canvas>
    <button id="saveBtn" onclick="saveImage()">Save Image</button>

    <script>
        function saveImage() {
            var canvas = document.getElementById('canvas');
            var dataURL = canvas.toDataURL();

            var link = document.createElement('a');
            link.download = 'canvas-image.png';
            link.href = dataURL;
            link.click();
        }
    </script>
</body>
</html>


In this example, we have a canvas element with an id of "canvas" and a button element with an id of "saveBtn". When the button is clicked, the saveImage() function is called. This function gets the data URL of the canvas image using the toDataURL() method and creates a download link for the image. Finally, it triggers a click event on the link element to download the image.