简体   繁体   English

HTML5 Canvas:未定义绘制

[英]HTML5 Canvas: draw is not defined

I am trying to follow the Mozilla HTML5 Canvas tutorial here . 我试图按照Mozilla的HTML5画布教程这里 but I get the error: 但是我得到了错误:

Uncaught ReferenceError: draw is not defined 

I have my script as such: 我有这样的脚本:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

 <script type="application/javascript">
$(function() {

function draw() {
      var canvas = document.getElementById("main");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
    }


});

</script>


</head>
 <body onload="draw();">
   <canvas id="main" width="150" height="150"></canvas>


</body>

I have experimented with placing the scripts both before and after the canvas element, but I get no change. 我已经尝试过将脚本放置在canvas元素之前和之后,但没有任何变化。

Would anyone know what Im doing wrong? 有人知道我在做什么错吗?

You are mis-using the jQuery here. 您在这里误用了jQuery。 Now your draw() method is only available (and declared) in the ready() method called by jQuery. 现在,您的draw()方法仅在jQuery调用的ready()方法中可用(并声明)。 Make the function global, and skip the jQuery part. 使函数成为全局函数,然后跳过jQuery部分。

 <script type="text/javascript">
   function draw() {
      var canvas = document.getElementById("main");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
  }
</script>

You see the $(function(){ ... }); 您会看到$(function(){ ... }); is a short-hand for the $(document).ready() , which are used as a call-back when all DOM-elements are loaded. $(document).ready()的简写,当加载所有DOM元素时,它们用作回调。 In your case that is not needed, since your draw() method is called by the body onload event anyways! 在您不需要的情况下,因为无论如何,body onload事件都会调用您的draw()方法! :-) :-)

An alternative to the above answer could be to quit using the inline call to draw() and remove the function header so it directly goes into it on load. 上述答案的替代方法是使用对draw()的内联调用退出并删除函数标头,以便它在加载时直接进入该标头。

<script type="application/javascript">
$(function() {
      var canvas = document.getElementById("main");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
});
</script>

Then your body will be freed: 然后您的身体将被释放:

<body>
<canvas id="main" width="150" height="150"></canvas>
<!-- ... -->

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

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