2012-09-11 110 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