2012-03-20 5 views
2

私はキャンバスを使用して、テキストと2つの画像を表示するためのJavaScript関数を使用しています。私が実行している問題は、クリックが機能を実行してテキストを表示することですが、必ずしも画像を配置するとは限りません。もう一度クリックすると、画像が表示されます。この動作はすべてのブラウザで一貫しています。コマンドは遅くはなく、最初に画像を表示することができません。 TIAHTML5キャンバスdrawImageが最初のクリックで機能しない

// JavaScript Document 

    function manualsTxt() { 
     var theCanvas = document.getElementById('Canvas1'); 
     if (theCanvas && theCanvas.getContext) { 
      var ctx = theCanvas.getContext("2d"); 

      if (ctx) { 
       var img1 = new Image(); 
       var img2 = new Image(); 
       var img3 = new Image(); 
       img1.src = "images/InRoads2004.png"; 
       img2.src = "images/XMUp.png"; 
       img3.src = "images/XM.png"; 

       //clear canvas 
       ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height); 

       // .drawImage (src, posX, posY); 
       ctx.drawImage (img1, 50, 325); 
       ctx.drawImage (img2, 250, 325); 
       ctx.drawImage (img3, 450, 325); 

       ctx.textBaseline = 'bottom'; 
       ctx.font   = 'bold 30px sans-serif'; 
       ctx.fillStyle = '#671420'; 
       ctx.fillText ('InRoads Manuals', 60, 30); 

       ctx.fillStyle = '#000'; 
       ctx.font   = 'italic bold 16px sans-serif'; 
       ctx.textBaseline = 'top'; 
       ctx.fillText ('MJM Consulting has published several InRoads training', 80, 60); 
       ctx.fillText ('manuals that have been used all over the world. We have', 90, 80); 
       ctx.fillText ('utilized our training manuals in all of our on-site trainings', 100, 100); 
       ctx.fillText ('for dozens of civil engineering firms and Department of', 105, 120); 
       ctx.fillText ('Transportations. Our manuals were one of the first to follow', 110, 140); 
       ctx.fillText ('a typical civil design project format. Our manuals are easy', 115, 160); 
       ctx.fillText ('to follow and contain a cd with a self-installing data set.', 115, 180); 
       ctx.fillText ('While our manuals are listed on other sites such as Amazon.com,', 115, 220); 
       ctx.fillText ('ordering direct from us is the only place you will get a', 110, 240); 
       ctx.fillText ('full color version of the manual.', 105, 260); 

      } 
     } 
    } 
+0

キャッシュに問題があるようです。この機能を実行する前に画像をプリロードしていますか? – rcdmk

答えて

8

画像が読み込まれるのを待っているわけではないので、

var img = new Image(); // Create new img element 
img.onload = function(){ 
    // execute drawImage statements here 
}; 
img.src = 'myImage.png'; // Set source path 

描画する前に、各画像に対してonloadイベントが発生していることを確認してください。複数の画像があり、何か複雑にしたくない場合は、pxloaderのように、これを行うライブラリがあります。

+0

ご意見ありがとうございます。私は先に進み、ソースを含むイメージを定義する別の.jsファイルを作成しました。このファイルは最初に読み込まれ、ユーザーがイメージを必要とするリンクをクリックすると、それらは既に読み込まれています。どうもありがとうございます!!!これは私を夢中にしていた@@@ – Prostang

関連する問題