尝试将带按钮的HTML画布下载为图像时的有趣下载错误 [英] Interesting download error when trying to download html canvas as image with button

查看:39
本文介绍了尝试将带按钮的HTML画布下载为图像时的有趣下载错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我第一次单击该按钮时,它不起作用.在我第二次点击它下载1张图片.我的第三次点击下载2张图片.在我的第4次点击上,它下载了3张图片.所以1-0、2-1、3-2、4-3.它们也会立即下载,它不会询问将文件保存在何处.

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>

我刚刚开始学习JavaScript.我正在尝试通过检查应用程序来学习.我不明白为什么会这样,因此无法解决问题.

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.

推荐答案

您现在基本上正在做两件事.

you are basically doing two things now.

因此,当有人单击按钮时,您将调用函数 xyz .在其中附加另一个Click侦听器,以便第二次同时触发 xyz 和该侦听器.

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.

您可以这样编写 xzy :

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

这应该只需单击一次即可下载您的 download.png 文件.

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.

我希望这是有道理的,因此请注意,使用 onclick 时不必进行绑定.

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

但是,如果您更喜欢非内联脚本,也可以这样做

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

这篇关于尝试将带按钮的HTML画布下载为图像时的有趣下载错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆