删除部分img src

时间:2018-07-30 07:35:30

标签: javascript html

我下面有这段代码,当我单击捕获按钮并下载图像时,会在我的img src前面添加一个链接。

问题是我正在尝试制作它,以便启动下载后,它会删除我在img src中添加的链接,因此它将返回到此https://pbs.twimg.com/profile_images/995985538556530690/7q_RKG2e_400x400.jpg

有没有简单的方法可以做到这一点?任何帮助将不胜感激谢谢

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.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">
        <div class="jobs-panel">
            <img id="imageID"  src="https://pbs.twimg.com/profile_images/995985538556530690/7q_RKG2e_400x400.jpg"
                width="300" height="300">
        </div>
    </div>
    <button type="button" onclick="sendData()" ;>Capture!</button>
    <a id="test" href="#"></a>
</body>

</html>

<script>
 
 function sendData() {
  html2canvas(document.getElementById('capture'), {
    allowTaint: false,
    useCORS: true
  }).then(function(canvas) {
    $('#imageID').attr('src', function(index, src) {
      return 'https://cors-anywhere.herokuapp.com/' + src;
    });
    $('#test').attr('href', canvas.toDataURL('image/png'));
    $('#test').attr('download', 'Test.png');
    $('#test')[0].click();

  });
}

</script>

1 个答案:

答案 0 :(得分:1)

将原始src保存在变量中:

function sendData() {
  const origSrc = $('#imageID').attr('src');

然后在src设置之后再次设置click()

  $('#test')[0].click();
  $('#imageID').attr('src', origSrc);
});

https://jsfiddle.net/snymf90t/

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.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">
    <div class="jobs-panel">
      <img id="imageID" src="https://pbs.twimg.com/profile_images/995985538556530690/7q_RKG2e_400x400.jpg" width="300" height="300">
    </div>
  </div>
  <button type="button" onclick="sendData()" ;>Capture!</button>
  <a id="test" href="#"></a>
</body>

</html>

<script>
  function sendData() {
    const origSrc = $('#imageID').attr('src');
    html2canvas(document.getElementById('capture'), {
      allowTaint: false,
      useCORS: true
    }).then(function(canvas) {
      $('#imageID').attr('src', function(index, src) {
        return 'https://cors-anywhere.herokuapp.com/' + src;
      });
      $('#test').attr('href', canvas.toDataURL('image/png'));
      $('#test').attr('download', 'Test.png');
      $('#test')[0].click();
      $('#imageID').attr('src', origSrc);
    });
  }
</script>