繁体   English   中英

如何在从JS表单中加载的JS中创建一个值,定义为JS进入绘制循环

[英]How can I make a value in JS loaded from a HTML form stay defined as JS enters draw loop

当我从绘制循环中获取它定义的HTML值时,但是如果我在它进入循环之前加载它似乎忘记了它。

这是我将其缩小到的代码:

<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>

像这样代码不起作用。 文本说价值未定义。 但是,如果我将“var value = do ...”移动到绘制函数之后,它就会得到它。

我需要在draw函数之外定义值。 我怎样才能做到这一点?

谢谢

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

我认为你错了,因为具有id uniqueID的元素在draw函数之外的任何地方都不存在。 这是因为您的脚本块在具有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>

当身体尚未加载时,你正在做这个。

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM