zigg75483
zigg75483

Reputation: 45

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

Upvotes: 0

Views: 83

Answers (2)

Quentin
Quentin

Reputation: 943124

You declare a bunch of variables inside the anonymous function you assign to 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.

Move setInterval and the draw function declaration inside the anonymous function you assign to 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>

Upvotes: 5

Scott
Scott

Reputation: 5369

Just a few issues with variable scope, among other things mentioned by @Quentin. You were defining local variables ctx, W, and H inside window.onload, which isn't accessible from 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.

Upvotes: 1

Related Questions