JavaScript似乎没有创建假圈

时间:2012-09-11 19:13:23

标签: php javascript

javascript似乎没有创建假圈,if语句中的else echo。我是以错误的顺序编写javascript的吗?我知道它不是php,因为正确的div显示在源代码中。

             

    </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 个答案:

答案 0 :(得分: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>