繁体   English   中英

Javascript未显示在浏览器中

[英]Javascript not showing up in browser

我正在本地主机上创建Web应用程序,但浏览器页面始终显示为空白,这是怎么做的? 谢谢

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

您可以在分配给onload的匿名函数中声明一堆变量。 它们不是全局变量。

然后,您尝试(间隔)将它们作为全局变量进行访问。

如果您在开发人员工具中查看控制台,则应该会看到一堆ReferenceErrors

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

@Quentin提到的其他一些关于范围可变的问题。 您正在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> 

为了将来参考,将脚本移动到body的末尾也是一个好主意,因此您不必为window load或DOMContentLoaded添加事件。

暂无
暂无

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

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