使用drawImage创建后,JavaScript保存图像

时间:2017-09-24 13:55:27

标签: javascript jquery html

我想让图片在创建后自动下载。到目前为止我有这个:



var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img1 = loadImage('https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png', main);

var img2 = loadImage('http://introcs.cs.princeton.edu/java/31datatype/peppers.jpg', main);
var imagesLoaded = 0;
function main() {
    imagesLoaded += 1;

    if(imagesLoaded == 2) {
        // composite now
        ctx.drawImage(img1, 0, 0);
        
        ctx.globalAlpha = 0.5;
        ctx.drawImage(img2, 0, 0);
        
        document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    }
}

function loadImage(src, onload) {
    // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
    var img = new Image();
    
    img.onload = onload;
    img.src = src;

    return img;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="512" height="512" id="canvas"></canvas>
&#13;
&#13;
&#13;

正确处理和创建图像,但未触发下载,并显示以下错误消息:

Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported

我已在CORS enabled image上阅读了MDN文档,并尝试将crossOrigin设置为匿名,但仍然无效。

有没有更好的方法来触发下载?

1 个答案:

答案 0 :(得分:1)

在设置crossOrigin之前,您需要设置图片src属性。

由于您无法访问服务器资源,因此设置了Access-Control-Allow-Origin响应标头,您将需要代理。

我使用https://cors.io作为这个答案,但是你可以使用它为你做的。

&#13;
&#13;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img1 = loadImage('https://cors.io/?https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png', main);


var img2 = loadImage('https://cors.io/?http://introcs.cs.princeton.edu/java/31datatype/peppers.jpg', main);
var imagesLoaded = 0;

function main() {
  imagesLoaded += 1;

  if (imagesLoaded == 2) {
    // composite now
    ctx.drawImage(img1, 0, 0);

    ctx.globalAlpha = 0.5;
    ctx.drawImage(img2, 0, 0);

    document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
  }
}

function loadImage(src, onload) {
  // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
  var img = new Image();

  img.onload = onload;
  img.crossOrigin = 'anonymous';
  img.src = src;

  return img;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="512" height="512" id="canvas"></canvas>
&#13;
&#13;
&#13;