user725913
user725913

Reputation:

Error when trying to make a canvas

I'm trying to use <canvas> to construct a grid. Please note - the code below is not my code and I remember finding it on stack overflow somewhere:

Here is my error:

Cannot call method 'getContext' of undefined

<!DOCTYPE html>
    <html>
        <head>  
    <style type="text/css">

        body {
        background: lightblue;
    }

    canvas {
        background: #fff;
        margin: 20px;
    }
        </style>

<!-- JQ Lib -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>



<script type="text/javascript">

          //grid width and height
    var bw = 400;
    var bh = 400;
    //padding around grid
    var p = 10;
    //size of canvas
    var cw = bw + (p*2) + 1;
    var ch = bh + (p*2) + 1;

    var canvas = $('#canvas').attr({width: cw, height: ch}).appendTo('body');
var context = canvas.get(0).getContext("2d");

    function drawBoard(){
        for (var x = 0; x <= bw; x += 40) {
            context.moveTo(0.5 + x + p, p);
            context.lineTo(0.5 + x + p, bh + p);
        }


        for (var x = 0; x <= bh; x += 40) {
            context.moveTo(p, 0.5 + x + p);
            context.lineTo(bw + p, 0.5 + x + p);
        }

        context.strokeStyle = "black";
        context.stroke();
    }

    drawBoard();
          </script>

        </head>


        <body>

        <canvas id="canvas">    </canvas>


        </body>
    </html>

The error is originating on this line:

 var canvas = $('#canvas').attr({width: cw, height: ch}).appendTo('body');

I have tried many different ways of doing this, but I keep getting the above error. Am I just making a mindless mistake here?

Upvotes: 0

Views: 347

Answers (1)

Quentin
Quentin

Reputation: 944443

You haven't defined $, which is a common (but meaningless) variable name used by a variety of different libraries including Protoype.js, Mootools and jQuery.

That syntax looks like jQuery so you will need to include the script for that library or rewrite it using built-in functions.

Upvotes: 1

Related Questions