2017-06-21 78 views
0

我知道這個問題已經被問了好幾次了,不過我還沒有找到 的解決方案。JavaScript canvas.toDataURL方法返回空白圖像

我想拍一張圖片,將它旋轉並放到HTML畫布中,做到這一點我使用另一個畫布旋轉圖片,但這部分效果很好,但是,當我嘗試拍攝圖像從第二個畫布使用.toDataUrl,它返回一個空白圖像。代碼如下

<!DOCTYPE html> 
    <html> 
    <head> 
     <title></title> 
    </head> 
    <body> 
    <canvas id=canvas height="400" width="400" style="border: 10px solid orange"></canvas> 
    <canvas id=canvasTransform height="183" width="183" style="border: 10px solid orange"></canvas> 
    <script type="text/javascript"> 
     //this is the canvas in which I want to put the rotated image 
     var canvas=document.getElementById("canvas"); 
     var context=canvas.getContext("2d"); 

     //and I use this one to rotate it 
     var canvasTransform=document.getElementById('canvasTransform'); 
     var contextTransform=canvasTransform.getContext("2d"); 

     var image=new Image(46,183); 
     image.onload=function(){ 
     contextTransform.drawImage(image,0,0); 
     } 
     image.src="Fireball.png"; 
     console.log(image.src); 
     //Now I rotate the context 
     contextTransform.rotate(-0.25*Math.PI); 
     //After doing this, I can see the rotated image in the second canvas, however, the following line returns a blank image 
     var rotatedImageURL=canvasTransform.toDataURL(); 
     console.log(rotatedImageURL); 
     //Finally, this part isn't wornking since I just draw a blank image 
     var rotatedImage=new Image(); 
     rotatedImage.onload=function(){ 
     context.drawImage(rotatedImage,0,0); 
     } 
     rotatedImage.src=rotatedImageURL; 

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

我一直在這裏停留一段時間,所以任何幫助表示讚賞。提前致謝!

回答

0

您可能需要等到繪製圖像後再調用toDataURL。火球僅在圖像加載後繪製,但在註冊onload事件處理程序後(但在實際加載之前)調用了旋轉(以及之後的所有內容)。

+0

謝謝!我終於明白髮生了什麼,移動除了我設置處理程序內部路徑的路線之外的所有內容,解決了問題 – JG55

+0

非常歡迎:)記住要將問題標記爲已解決! –