使用cors-anywhere.herokuapp下载图像

时间:2018-08-03 07:35:13

标签: javascript html html2canvas

我下面的代码包含图像和下载按钮。问题是,使用HTML2Canvas库下载外部图像会导致CORS问题,这就是为什么即时通讯使用此https://cors-anywhere.herokuapp.com/解决CORS问题,但它始终给我错误400 (Header required)

我不确定自己做错了什么,还是有更好的方法解决此问题,但是对您的帮助将不胜感激。

function sendData() {

  html2canvas(document.getElementById('capture'), {}).then(function(canvas) {
    downloadCanvas(document.getElementById('test'), canvas, 'test.png');
  });
}

function downloadCanvas(link, canvas, filename) {
  link.href = canvas.toDataURL();
  link.download = filename;
  link.click();
}
body {
  font-family: Arial;
}

.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
  margin-top: 10px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}


/* Style the buttons inside the tab */

.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
  border-bottom: 8px;
}


/* Change background color of buttons on hover */

.tab button:hover {
  background-color: #ddd;
}

#capture {
  overflow: visible;
}


/* Create an active/current tablink class */

.tab button.active {
  background-color: #ccc;
}


/* Style the tab content */

.tabcontent {
  display: none;
  padding: 6px 25px;
  border: 1px solid #ccc;
  border-top: none;
  -webkit-animation: fadeEffect 1s;
  animation: fadeEffect 1s;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  background-color: white;
}

.jobs-panel {
  display: table;
  max-height: 100%;
  width: 85%;
  background-color: #b7bcbe;
  margin-left: auto;
  margin-right: auto;
  margin-top: 25px;
  margin-bottom: 25px;
  padding-bottom: 20px;
  padding-top: 20px;
}

.tabwidth {
  width: 85%;
  margin: 0 auto;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<html>

<head>
  <meta charset="utf-8" />

  <link rel="shortcut icon" href="//#" />
  <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
  <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>

<body>
  <div id="capture">
    <img src="https://cors-anywhere.herokuapp.com/https://s22.postimg.cc/l2txqenox/Pikachu.png" width="300" height="300">
  </div>
  <button id="match-button" onclick="sendData();">capture</button>
  <a id="test" href="#"></a>

</body>

</html>

0 个答案:

没有答案