Javascript file (excanvas) not working whe

2019-08-17 18:41发布

问题:

This works:

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

This doesn't:

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

The only difference between the two is where I'm loading it in the page. Everything works fine when I load excanvas in the head. I get an error when I load it at the bottom of the body.

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

回答1:

RTFM:

The excanvas.js file must be included in the page before any occurrences of canvas elements in the markup. This is due to limitations in IE and we need to do our magic before IE sees any instance of in the markup. It is recommended to put it in the head.



回答2:

If you're looking to load excanvas asynchronously/conditionally, it is possible: https://stackoverflow.com/a/18520897/541023