2015-02-09 93 views
0

主要問題是我必須處理很多圖像。我不能爲所有這些屬性使用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

回答

1

瀏覽器出於非常好的安全原因不讓程序員導出跨域內容。您的私人銀行信息是跨域內容,您不希望使用畫布作爲導出設備給盜賊。

因此,在將跨域圖像繪製到畫布上後,立即禁用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[] 

} 
相關問題