DLaningham
DLaningham

Reputation: 23

Javascript Canvas Uncaught TypeError: document.getContext is not a function

I am trying to draw a simple canvas but my browser shows an error, I am doing this by a tutorial and wondering where the mistake is. Thanks in advance

  <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>doc</title>
        <link rel="stylesheet" href="style.css">

    </head>
    <body>
        <canvas id="c1"></canvas>
        <script src="js.js"></script>
    </body>
    </html>
   var canvas = document.getElementById('c1');
   var ctx = document.getContext('2d');
   ctx.fillRect(100,50,150,75);

Upvotes: 1

Views: 1149

Answers (2)

jared
jared

Reputation: 732

let ctxA = document.querySelector("#canvas1").getContext("2d");

let ctxB = document.querySelector("#canvas2").getContext("2d");

These lines grab the <canvas id='canvas1'> <canvas id='canvas2'> DOM elements and then identify the context of the respective canvas.

The context object is what contains all the drawing methods etc, so that's what you really want - you'll reference the context object much more often than the canvas object.

note that if you do want the canvas object you can reference it in the ctx.canvas property.

Upvotes: 0

wolfenrain
wolfenrain

Reputation: 309

The getContext is method of the canvas element.

So instead of document.getContext('2d') try canvas.getContext('2d')

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext for more information

Upvotes: 3

Related Questions