2017-06-21 4 views
0

この質問は既に何度か尋ねられていますが、私は の解決策をまだ見つけていません。JavaScript canvas.toDataURLメソッドが空白の画像を返す

イメージを回転して回転させてHTMLキャンバスに入れたいと思います。私はイメージを回転させる別のキャンバスを使用していますが、この部分はうまく動作します。 .toDataUrlを使用して2番目のキャンバスからイメージを取得すると、空のイメージが返されます。コードは次のとおりです

<!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を呼び出す前に、イメージを描画した後で待機する必要があります。 Fireballはイメージがロードされた後に描画されますが、rotate(およびそれ以降のすべて)はonloadイベントハンドラを登録した直後(実際にロードされる前)に呼び出されます。

+0

ありがとうございます!私は最終的に何が起こっているのか理解し、問題を解決したハンドラ内の画像へのパスを設定した行を除いてすべてを動かします。 – JG55

+0

あなたは非常に歓迎です。 –

関連する問題