0

I made the following script. When I push the button, the word "blood" moves, and push the button and it stops.

This script worked in Chrome but when I move the following scripts to the TOP line. (between var flag; and window.setInterval), an error happens saying

uncaught typeerror cannot call method 'getcontext' of null"

would you explain why it happens please?

var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d");

var y = 100;
var flag = false;

window.onload = setInterval(function(){
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");


ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);

ctx.fillStyle = "red";
ctx.font = "50px Helvetica";
ctx.fillText("blood", 200, y);

if(flag){
y++;
}

}, 30);

function start(){
flag = true;
}

function stop(){
flag = false;
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337

2 Answers2

1

If you run your code in a script element at the end of the html body, you can ensure that it doesn't try to get the canvas context before the DOM is ready. Also, I made an optimization to your code to cache the DOM lookup:

<html>
<head>
    <title>Canvas Scrolling Text</title>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script type="text/javascript">
        var y = 100;
        var flag = false;

        var canvas = document.getElementById("canvas"),
            ctx = canvas.getContext("2d");

        setInterval(function() {
            ctx.fillStyle = "black";
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            ctx.fillStyle = "red";
            ctx.font = "50px Helvetica";
            ctx.fillText("blood", 100, y);

            if(flag)
                y++;
        }, 30);

        function start()
        {
            flag = true;
        }

        function stop()
        {
            flag = false;
        }

        start();
    </script>
</body>

Here's a working jsFiddle.

Cameron Tinker
  • 9,634
  • 10
  • 46
  • 85
0

If you move it out of the onload function, then the DOM elements (specifically your canvas) don't exist yet. See https://stackoverflow.com/a/15564394/1370556 for more information on DOM content loaded events.

Community
  • 1
  • 1
lebolo
  • 2,120
  • 4
  • 29
  • 44