在Chrome中使用toDataURL有没有其他选择?

问题描述:

主要问题是我必须处理很多图像。我不能为所有这些属性使用crossOrigin属性。在Chrome中使用toDataURL有没有其他选择?

My code looks like this: 
<script> 
var c=document.getElementById('example'); 
var ctx=c.getContext('2d'); 
var LeftHand = new Image(); 
LeftHand.id="imq1"; 
var RightHand = new Image(); 
RightHand.id="imq2"; 
var Body = new Image(); 
Body.id="imq6"; 

boyBody.src = "https://getout-s3.s3.amazonaws.com/baseBody/boy-02.png"; 
LeftHand.src = "https://getout-s3.s3.amazonaws.com/NK4XtQvkZ4MGctZf_.hand(unisex)_13.png "; 
RightHand.src = "https://getout-s3.s3.amazonaws.com/OPdFPcU2sORgNmTy_.hand(unisex)_9.png "; 
Body.src = "https://getout-s3.s3.amazonaws.com/HRZqrTYSdJXGedgX_.Body_(m)7.png "; 

boyBody.onload = function() { 
ctx.drawImage(boyBody, 0, 0, boyBody.width/2, boyBody.height/2); 
ctx.drawImage(LeftHand, (899 - LeftHand.width/2)/2, (867 - LeftHand.height/2)/2, LeftHand.width/2, LeftHand.height/2); 
ctx.drawImage(Underwear, (599 - Underwear.width/2)/2, (845 - Underwear.height/2)/2, Underwear.width/2, Underwear.height/2); 
ctx.drawImage(Body, (599 - Body.width/2)/2, (557 - Body.height/2)/2, Body.width/2, Body.height/2); 
var img = c.toDataURL("image/png"); 
document.write('<img src="' + img + '" />'); 
}; 
</script> 
+0

为什么你需要''元素呢?为什么不只显示''元素? (如果需要第二个罐子的副本,则可以执行'newCanvas.drawImage(oldCanvas);',因为canvas元素是'drawImage'的有效参数。) – apsillers 2015-02-09 15:52:45

浏览器出于非常好的安全原因不让程序员导出跨域内容。您的私人银行信息是跨域内容,您不希望使用画布作为导出设备给盗贼。

因此,在将跨域图像绘制到画布上后,立即禁用context.toDataURL。对于context.getImageData,同样的禁用也是如此。 (context.getImageData是另一种导出画布内容的方式)。

要允许将画布内容导出到用户,您必须将所有图像托管在与您的网页相同的域中。

顺便说一句,你必须在绘制它们之前给你的所有元素加载时间。这是一个图像加载器,可以预先加载所有图像,然后在所有图像完全加载时调用start()。把你的ctx.drawImage放入start()。

// put the paths to your images in imageURLs[] 
var imageURLs=[]; 
imageURLs.push("https://getout-s3.s3.amazonaws.com/baseBody/boy-02.png"); 
imageURLs.push("https://getout-s3.s3.amazonaws.com/NK4XtQvkZ4MGctZf_.hand(unisex)_13.png"); 
// ...etc, for all images 

// the loaded images will be placed in imgs[] 
var imgs=[]; 

var imagesOK=0; 
loadAllImages(start); 

function loadAllImages(callback){ 
    for (var i=0; i<imageURLs.length; i++) { 
     var img = new Image(); 
     imgs.push(img); 
     img.onload = function(){ 
      imagesOK++; 
      if (imagesOK>=imageURLs.length) { 
       callback(); 
      } 
     }; 
     img.onerror=function(){alert("image load failed");} 
     img.crossOrigin="anonymous"; 
     img.src = imageURLs[i]; 
    }  
} 

function start(){ 

    // the imgs[] array now holds fully loaded images 
    // the imgs[] are in the same order as imageURLs[] 

}