尝试使用按钮将 html 画布下载为图像时出现有趣的下载错误

Interesting download error when trying to download html canvas as image with button(尝试使用按钮将 html 画布下载为图像时出现有趣的下载错误)

本文介绍了尝试使用按钮将 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.在那里你附加了另一个点击监听器,所以第二次,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 画布下载为图像时出现有趣的下载错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:尝试使用按钮将 html 画布下载为图像时出现有趣的下载错误

基础教程推荐