当我在页面底部加载它时,Javascript文件(excanvas)无法正常工作

时间:2010-06-18 21:25:36

标签: javascript excanvas

这有效:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

  <script src="/js/msgv/widgets/excanvas2.js" type="text/javascript"></script>
  <script type="text/javascript" charset="utf-8">
    function canvasTest(){
      console.log("beginning canvasTest");
      var b_canvas = document.getElementById("regularCanvas");
      var b_context = b_canvas.getContext("2d");
      b_context.fillRect(50, 25, 150, 100);
    }
  </script>

</head>

<body onLoad="canvasTest()">
    <canvas id="regularCanvas" style="border: 1px dotted; float: left;" class="clear" height="225" width="300"></canvas>
</body>
</html>

这不是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

两者之间的唯一区别是我在页面中加载它。当我在头部加载excanvas时,一切正常。当我把它装在身体的底部时,我收到一个错误。

  <script type="text/javascript" charset="utf-8">
    function canvasTest(){
      console.log("beginning canvasTest");
      var b_canvas = document.getElementById("regularCanvas");
      var b_context = b_canvas.getContext("2d");
      b_context.fillRect(50, 25, 150, 100);
    }
  </script>

</head>

<body onLoad="canvasTest()">
    <canvas id="regularCanvas" style="border: 1px dotted; float: left;" class="clear" height="225" width="300"></canvas>
  <script src="/js/msgv/widgets/excanvas2.js" type="text/javascript"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

RTFM

  

在标记中出现任何canvas元素之前,必须在页面中包含excanvas.js文件。这是由于IE中的限制,我们需要在IE看到标记中的任何实例之前做我们的魔术。建议把它放在头上。

答案 1 :(得分:0)

如果您想要异步/有条件地加载excanvas,可以: https://stackoverflow.com/a/18520897/541023