user3565953
user3565953

Reputation: 1

"var canvas = document.getElementById("canvas")" can't be a global variable?

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

Upvotes: 0

Views: 1768

Answers (2)

Cameron Tinker
Cameron Tinker

Reputation: 9789

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.

Upvotes: 1

lebolo
lebolo

Reputation: 2160

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.

Upvotes: 0

Related Questions