2012-09-11 57 views
0

javascript似乎並沒有在if語句中創建假圈,else echo。我寫錯了順序的JavaScript?我知道它不是PHP,因爲正確的div顯示在源代碼中。javascript似乎並沒有創建假圈

</style> 
    <script> 
     window.onload = function() { 
     //uetr circle 
     var canvas = document.getElementById("Canvas"); 
     var context = canvas.getContext("2d"); 
     var centerX = canvas.width/2; 
     var centerY = canvas.height/2; 
     var radius = 70; 
     context.beginPath(); 
     context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); 
     context.fillStyle = "#00FF7F"; 
     context.fill(); 
     context.lineWidth = 5; 
     context.strokeStyle = "black"; 
     context.stroke(); 

     //false circle 
     var canvas = document.getElementById("Canvas1"); 
     var context = canvas.getContext("2d"); 
     var centerX = canvas.width/2; 
     var centerY = canvas.height/2; 
     var radius = 70; 
     context.beginPath(); 
     context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); 
     context.fillStyle = "#B0171F"; 
     context.fill(); 
     context.lineWidth = 5; 
     context.strokeStyle = "black"; 
     context.stroke(); 
     }; 

    </script> 
    </head> 
    <body> 
     <?php 

     $visible = true; 

     if($visible){ 
      echo "<div id='unhidden'><canvas id='Canvas' width='578' height='200'></canvas></div>"; 
     } 
     else{ 
      echo "<div id='hidden'><canvas id='Canvas1' width='578' height='200'></canvas></div>"; 
     } 
     ?> 
    </body> 
</html> 
+1

在你的if語句,你的畫布對各行不同的ID - 我第一個想到的應該是'Canvas1 '以匹配第二個和javascript參考。 – andrewsi

回答

3

您迴應只有一個canvas標籤。你的腳本試圖繪製兩個元素。一旦它遇到一個不存在的元素,它會中斷 - 檢查你的錯誤控制檯。如果你迴應「真實」的圓圈,它將在繪製第一個圓圈後中斷 - 如果你迴應「假」圓圈,它將在繪畫任何東西之前中斷。

無論是檢查canvas !== null,或更好地取決於知名度執行只有一個功能:

<script type="text/javascript"> 
window.onload = function() { 
    function drawCircle(canvasid, color) { 
     var canvas = document.getElementById(canvasid); 
     if (!canvas) // check for null 
      return; 
     var context = canvas.getContext("2d"); 
     var centerX = canvas.width/2, 
      centerY = canvas.height/2; 
     var radius = 70; 
     context.beginPath(); 
     context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); 
     context.fillStyle = color; 
     context.fill(); 
     context.lineWidth = 5; 
     context.strokeStyle = "black"; 
     context.stroke(); 
    } 

    <?php 
if (true) 
    echo " drawCircle('canvas', '#00FF7F');"; 
else 
    echo " drawCircle('canvas', '#B0171F');"; 
?> 
}; // end onload function 
</script> 

<body> 
    <?php 
    if (true){ 
     echo "<div id='unhidden'>"; 
    else 
     echo "<div id='hidden'>"; 
    ?> 
    <canvas id='canvas' width='578' height='200'></canvas> 
    </div> 
</body> 
+0

我明白了,但回聲不會將屬性添加到JS,有人知道,這是如何實現的。 – HansWorst

+0

你的意思是「echo不會將屬性添加到JS」? – Bergi