简体   繁体   English

Javascript未显示在浏览器中

[英]Javascript not showing up in browser

I am making my web app on localhost, but the browser page keeps showing up as blank, what am I doing wrong? 我正在本地主机上创建Web应用程序,但浏览器页面始终显示为空白,这是怎么做的? Thanks 谢谢

<html>
<head>
<script>

window.onload = function() {
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
W = window.innerWidth,
H = window.innerHeight;


setInterval(draw, 33);

function draw() {
ctx.globalcompositeOperation = "source-over";
ctx.fillStyle = "black";
ctx.fillRect(0,0,W,H);
}
}

</script>
</head>

<body>
    <canvas id="canvas"></canvas>

You declare a bunch of variables inside the anonymous function you assign to onload . 您可以在分配给onload的匿名函数中声明一堆变量。 They are not globals. 它们不是全局变量。

You then try to (on an interval) access them as globals. 然后,您尝试(间隔)将它们作为全局变量进行访问。

If you look at the Console in your developer tools you should expect to see a bunch of ReferenceErrors . 如果您在开发人员工具中查看控制台,则应该会看到一堆ReferenceErrors

Move setInterval and the draw function declaration inside the anonymous function you assign to onload . 移动setIntervaldraw分配给匿名函数内部函数声明onload

 window.onload = function () { var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"), W = window.innerWidth, H = window.innerHeight; setInterval(draw, 33); function draw() { ctx.globalcompositeOperation = "source-over"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, W, H); } } 
  <canvas id="canvas"></canvas> 

Just a few issues with variable scope, among other things mentioned by @Quentin. @Quentin提到的其他一些关于范围可变的问题。 You were defining local variables ctx , W , and H inside window.onload , which isn't accessible from draw . 您正在window.onload中定义局部变量ctxWH ,而draw无法访问该局部变量。

 <html> <head> <script> var ctx, W, H; window.onload = function() { var canvas = document.getElementById("canvas"); W = window.innerWidth; H = window.innerHeight; ctx = canvas.getContext("2d"); setInterval(draw, 33); } function draw() { ctx.globalCompositeOperation = "source-over"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, W, H); } </script> </head> <body> <canvas id="canvas"></canvas> </body> </html> 

For future reference, it's also a good idea to move scripts to the end of the body , so you don't have to add events for the window load or DOMContentLoaded . 为了将来参考,将脚本移动到body的末尾也是一个好主意,因此您不必为window load或DOMContentLoaded添加事件。

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

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