使用javascript从画布下载图像

时间:2017-10-12 21:46:45

标签: javascript html

我试图通过以下代码下载加载的图像,但这不起作用(不下载) 我需要在我的电脑的本地存储中下载加载的图像
我收到错误 - >安全例外

<!DOCTYPE html>
<html>
  <body>
    <img  id="imageId" src="https://lh3.googleusercontent.com/Eaxq_eRyitzuD_wcptI_RBva0CiqzWPztZolEDfKrdftel4ENSf2XinyJyjPecUrJQ"	>
    <button onclick="storeImageIntoLocal()">Copy Image </button>
    <script>
      function storeImageIntoLocal() {
        var img=document.getElementById('imageId');
        img.crossOrigin = "anonymous";
        var canvas = document.createElement("canvas");
        canvas.width = (img.width+50);
        canvas.height = (img.height+15);
        var body = document.getElementsByTagName("body")[0];
        body.appendChild(canvas);
    		
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
    	
        var dataURL = canvas.toDataURL("image/png"); // this is not working 
    	alert("converted");
    	
    	localStorage.setItem("image",dataURL);// this is not working 

        //    var base64dataFinal= dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
      }

    </script>
  </body>
</html>

2 个答案:

答案 0 :(得分:0)

localStorage.setItem("image", dataURL);不会触发文件下载。这是一个首先调用的错误的API。

您需要创建一个<a> html元素并为其href属性分配dataURL值,然后在其上触发click()。 有关详细信息,请参阅此问题:https://stackoverflow.com/a/26050821/482868

var downloadLink = document.createElement('a');
downloadLink.href = dataURL;
downloadLink.download = 'myImage.png';

document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

答案 1 :(得分:0)

您应该通过Image()创建新图像。 这是解决方案:

function storeImageIntoLocal() {
     var img=document.getElementById('imageId');
     var imgI = new Image();
     imgI.setAttribute('crossOrigin', 'anonymous');
     imgI.src = img.src;
     var canvas = document.createElement("canvas");
     canvas.width = (img.width+50);
     canvas.height = (img.height+15);

     var body = document.getElementsByTagName("body")[0];
     body.appendChild(canvas);
    		
     var ctx = canvas.getContext("2d");
     ctx.drawImage(imgI, 0, 0);
    	
     var dataURL = canvas.toDataURL("image/jpg"); 
     alert("converted");

     localStorage.setItem("image",dataURL);
 }
此代码适用于我