0

I have a script that's broken and its currently trying to upload form contents to imgbb. I dont want that, instead i want it to save the canvas contents to a jpg file locally on visitors web browser. How do i do this? Here's the current code:

const formData = new FormData();
            formData.append("image", canvas.toDataURL().split(',')[1])
            var req = new XMLHttpRequest()
            req.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    response = JSON.parse(this.response)
                    console.log(response)
                    url = response.data.image.url
                    $('#Loading').hide();
                    $('#URL').val(url).fadeIn();
                }
            }
            req.open("POST", 'https://api.imgbb.com/1/upload?key=xxxxxxxxxxxxxxxxxxxxxxxxxx', true)
            req.send(formData)

        },

Ive tried the tutorial at How To Save Canvas As An Image With canvas.toDataURL()? but it doesnt work and also is incompatible with many browsers.

Everything i try doesnt work. Ive been going insane for the last day.

Ruok2bu
  • 13
  • 3
  • 1
    [doesn't work is not a useful description of the problem](https://idownvotedbecau.se/itsnotworking/) – Quentin Jul 30 '23 at 21:08
  • 1
    "also is incompatible with many browsers" — I can't think of any browsers that don't support the techniques used by the answers there and are relevant today. You don't need to support Microsoft Internet Explorer 8 do you? – Quentin Jul 30 '23 at 21:10

1 Answers1

0

To save a canvas to a JPEG file you can use the URL generated using toDataURL and create a download link that will be automatically clicked

// Convert canvas content to JPEG data URL
const dataURL = canvas.toDataURL('image/jpeg');

// Create a download link
const link = document.createElement('a');
link.href = dataURL;
link.download = 'canvas_image.jpeg';

// Simulate a click on the link to trigger the download
link.click();

This is the most basic example and should work in a regular environment, can you provide more details to check why would that not work?