一次在多个图像上启用CORS

时间:2015-04-14 13:51:46

标签: javascript html5 html5-canvas cors

我知道我们可以使用此代码在单个图像上启用CORS

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

var img = new Image();
img.crossOrigin = '';
img.src = 'http://crossdomain.com/image.jpg';

canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);

有没有办法一次为多个图片网址执行此操作?

2 个答案:

答案 0 :(得分:1)

网址数组

要加载多个启用CORS请求的图像,您可以使用一个实用的数组。

需要注意的一点是服务器可以拒绝请求CORS。在这些情况下,浏览器可能无法加载图像,因此您需要提前知道是否需要请求CORS。

示例装载程序

var urls = [url1, url2, url3, ...];   // etc. replace with actual URLs
var images = [];                      // store the loaded images
var i = 0, len = urls.length;
var count = len;                      // for load and error handlers

for(; i < len; i++) {
     var img = new Image();
     img.onload = loadHandler;
     img.onerror = img.onabort = errorHandler;
     img.crossOrigin = "";            // enable CORS request
     img.src = urls[i];               // set src last
     images.push(img);                // store in array
}

function loadHandler() {
    if (!--count) callback();         // loading done
}

function errorHandler() {
   // handle errors here
   loadHandler();                     // make sure to update counter/callback
}

function callback() {
    // ... ready, continue from here
}

演示

&#13;
&#13;
var urls = [
      "http://i.imgur.com/0LINzxs.jpg",   // random urls from imgur..
      "http://i.imgur.com/6ksiMgS.jpg", 
      "http://i.imgur.com/aGQSLi9.jpg"
    ];
    var images = [];                      // store the loaded images
    var i = 0, len = urls.length;
    var count = len;                      // for load and error handlers
    
    for(; i < len; i++) {
         var img = new Image();
         img.onload = loadHandler;
         img.onerror = img.onabort = errorHandler;
         img.crossOrigin = "";            // enable CORS request
         img.src = urls[i];               // set src last
         images.push(img);                // store in array
    }

    function loadHandler() {
        if (!--count) callback();         // loading done
    }

    function errorHandler() {
       // handle errors here
       loadHandler();                     // make sure to update
    }

    function callback() {
        // ... ready, continue from here
        console.log(images);
        var ctx = document.querySelector("canvas").getContext("2d");
        ctx.drawImage(images[0], 0, 0);
        ctx.drawImage(images[1], 0, 0);
        ctx.drawImage(images[2], 0, 0);
        console.log(ctx.canvas.toDataURL());  // OK if CORS is OK!
    }
&#13;
<canvas></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:-2)

将srcs放在一个数组中并迭代它们

工作小提琴 https://jsfiddle.net/ps50po4z/ 这允许您使用来自不同来源的多个图像并显示它们。 使用此函数作为模板迭代所有cors src图像

<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        // get num of sources
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var sources = {
        darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
        yoda: 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg'
      };

      loadImages(sources, function(images) {
        context.drawImage(images.darthVader, 100, 30, 200, 137);
        context.drawImage(images.yoda, 350, 55, 93, 104);
      });

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