0

When I, from within the draw loop, get the HTML value it's defines, but if I load it before it enters the loop it seems to forget it.

This is the code I've narrowed it down to:

<html>
 <head>
  <script type="application/javascript">
    setInterval(draw,120);
    var value = document.getElementById("uniqueID").value

    function draw() {
      var canvas = document.getElementById('canvas');

      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");
        ctx.strokeText(value, 200, 200);
      }
    }
  </script>
 </head>
 <body onload="draw();">
   <canvas id="canvas" width="500" height="500"></canvas>
   <input type="text" name="name" id="uniqueID" value="5" /><br>
 </body>
</html>

Like this the code doesn't work. The text says that value is undefined. But if i move the "var value = do..." to after the draw function it gets it.

I need to define the value outside of the draw function. How can I do that?

Thanks

4

2 回答 2

1

但是如果我将“var value = do ...”移动到draw函数之后,它就会得到它。

我认为您弄错了,因为具有 id uniqueID 的元素在绘图函数之外的任何地方都不存在。这是因为您的脚本块是在具有 uniqueID 的元素之前执行的。

您可以在创建元素后添加整个脚本块并添加文档类型定义:

<!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
   <canvas id="canvas" width="500" height="500"></canvas>
   <input type="text" name="name" id="uniqueID" value="5" /><br>
  <script type="application/javascript">
    setInterval(draw,120);
    var value = document.getElementById("uniqueID").value

    function draw() {
      var canvas = document.getElementById('canvas');

      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");
        ctx.strokeText(value, 200, 200);
      }
    }
  </script>
 </body>
</html>
于 2013-05-27T08:26:20.047 回答
1

当身体尚未加载时,您正在头部执行此操作。

var value = document.getElementById("uniqueID").value

您需要在 body load 函数中移动所有代码。

<html>
    <head>
        <script type="application/javascript">
        function OnLoad ()
        {
            setInterval(draw,120);
            var value = document.getElementById("uniqueID").value
            draw();
        }


        function draw() {
        var canvas = document.getElementById('canvas');

        if (canvas.getContext) {
        var ctx = canvas.getContext("2d");
        ctx.strokeText(value, 200, 200);
      }
    }
    </script>
 </head>
 <body onload="OnLoad()">
        <canvas id="canvas" width="500" height="500"></canvas>
        <input type="text" name="name" id="uniqueID" value="5" /><br>
 </body>
</html>
于 2013-05-27T08:29:33.583 回答