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

懵懂的女人 提交于 2020-11-30 00:12:46

问题


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.


回答1:


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! ✌️



来源:https://stackoverflow.com/questions/64878821/interesting-download-error-when-trying-to-download-html-canvas-as-image-with-but

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!