2013-07-25 69 views
2

我一直在試圖找到一種將畫布保存到文件的方法。我的圖片太大而無法使用dataToUrl,所以我一直在嘗試各種各樣的toblob方法。看起來,當使用圖案填充時,toblob不起作用。如果有可能這樣工作,或者如果有另一種方法可以實現這一目標,任何人都可以對我有所幫助嗎?由於使用圖案填充時,canvas.toblob失敗

jfiddle example

<!DOCTYPE html> 
<html> 
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas> 

<script src="jquery.min.js"></script> 
<script src="canvas-to-blob.js"/></script> 
<script src="FileSaver.js-master\FileSaver.js"></script> 
<script> 
var c = document.getElementById("myCanvas"); 
var ctx = c.getContext("2d"); 
ctx.clearRect(0, 0, c.width, c.height); 
var img = new Image(); 
img.src = "http://www.w3schools.com/tags/img_lamp.jpg"; 
var pat = ctx.createPattern(img, "repeat"); 
ctx.rect(0, 0, 150, 100); 

//Works with color, but not with pattern 
ctx.fillStyle = pat; 
//ctx.fillStyle = 'blue'; 

ctx.fill(); 

try { 
    var isFileSaverSupported = !! new Blob(); 
} catch (e) { 
    alert(e); 
} 
alert("toBlob"); 
c.toBlob(function (blob) { 
    alert("success"); 
    saveAs(blob, "TruVue.png"); 
}); 
</script> 
</html> 

回答

3

的原因是由於CORS,來自其他域的圖像被限制 - 你可以告訴他們在畫布上,但你不能提取自己的位圖。

由於toBlob是一個位圖提取方法,如toDataURLgetImageData您將無法使用這些圖像。

有幾個變通的:

  • 將圖像上傳到自己的服務器(如您使用的頁面相同的域)從那裏加載它。
  • 修改其他服務器以包含Access-Control-Allow-Origin標頭(在這種情況下,它可能不可用)。
  • 使用自己的服務器作爲圖像代理

BTW:您還應該使用圖像的onload事件,以確保圖像被使用圖像之前正確加載:

var img = new Image(); 
img.onload = drawFunction; 
img.src = "http://www.w3schools.com/tags/img_lamp.jpg"; 

function drawFunction() { 
    /// draw here 
} 
+0

謝謝,我所有這些都是新的,所以我沒有CORS限制,我只是認爲w3schools將是一個容易獲得圖像的地方。使用的真實圖像在同一個域上。我只測試了本地機器上的所有內容,但結果相同。我現在將在服務器上測試它,看看是否有所作爲。 –

+1

@DavidRay我忘了提及用'file://協議加載的圖像也被認爲不是來自同一個原點,如果這是你在本地使用的。 – K3N

+0

服務器上的結果相同。 –