Aycan Candar
Aycan Candar

Reputation: 63

Interesting download error when trying to download html canvas as image with button

When I first click the button it doesn't work. On my second click it downloads 1 picture. My 3rd click it downloads 2 pictures. On my 4th click it downloads 3 pictures. So 1-0, 2-1, 3-2, 4-3. They are also downloaded immediately, it doesn't ask where to save.

js:

  function xyz(){
  const text =canvas.api.getCanvasAsImage();
  const download = document.getElementById('download');
  download.addEventListener('click', function(e) {
  var link = document.createElement('a');
  link.download = 'download.png';
  link.href = text;
  link.click();
  link.delete;
});
}

html:

<button  onclick="xyz()" id="download">Download</button>

I have just started learning javascript. I'm trying to learn by examining an application. I did not understand why these is happening and therefore could not solve the problem.

Upvotes: 0

Views: 833

Answers (1)

Rebelchris
Rebelchris

Reputation: 86

you are basically doing two things now.

So when someone clicks the button you call the function xyz. In there you attach another click listener so the second time, both xyz and that listener will fire.

You can write your xzy like this:

function xyz(){
  const text = canvas.api.getCanvasAsImage();
  var link = document.createElement('a');
  link.download = 'download.png';
  link.href = text;
  link.click();
  link.delete;
}

This should just download your download.png file once every click.

As for the location, this is not default behaviour, it will just download to your downloads, this happens because we force a image download. It's not a user optional thing here.

I hope this makes sense, so be aware when using the onclick you don't have to do the binding.

Optional method

You could however also do this if you would prefer non inline scripts

<button  id="download">Download</button>
const text = canvas.api.getCanvasAsImage();
const download = document.getElementById('download');
  
download.addEventListener('click', function(e) {
  var link = document.createElement('a');
  link.download = 'download.png';
  link.href = text;
  link.click();
  link.delete;
});

Hope this helps you! ✌️

Upvotes: 2

Related Questions