Henrik
Henrik

Reputation: 703

How do I get functions defined outside of a canvas draw loop to be useable within the loop?

I can't get this simple thing to work.

I'm defining a function before I enter the draw loop. But it won't work. Put the code from the function directly into the loop and it works like a charm. How do I get the function defined outside of the draw loop to work within it?

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body onload="draw();">
        <canvas id="canvas" width="500" height="500"></canvas>
        <script type="application/javascript">
            setInterval(draw,120);
            var canvas = document.getElementById('canvas');


            var dot = function(px,py) {
            fillStyle = "rgb(0,0,0)";
            ctx.fillRect(px,py,12,12)
            };

            function draw() {
                if (canvas.getContext) {
                    var ctx = canvas.getContext("2d");
                    dot(34,34);
                }
            }
        </script>
    </body>
</html>

Upvotes: 0

Views: 136

Answers (1)

aaronman
aaronman

Reputation: 18750

When you define it outside of draw the ctx you are using is different because of js' scoping rules. What you should do is pass the context into the function.

    var dot = function(ctx,px,py) {
        fillStyle = "rgb(0,0,0)";
        ctx.fillRect(px,py,12,12)
    };

        function draw() {
            if (canvas.getContext) {
                var ctx = canvas.getContext("2d");
                dot(ctx,34,34);
            }
        }

Another thing you could consider is to make the context a global variable like the canvas since you will be using it a lot.

    var ctx = canvas.getContext("2d");
    var dot = function(px,py) {
        fillStyle = "rgb(0,0,0)";
        ctx.fillRect(px,py,12,12)
     };

        function draw() {
            if (canvas.getContext) {
                dot(34,34);
            }
        }

Upvotes: 1

Related Questions