0

I'm trying to use getContext('2d'); using jQuery. I have seen this question, but it doesn't seem to work. It could possibly be from updates, since the question was asked near 9 years ago. I am adding <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script> in the head, but using a different <script> tag for my javascript (shouldn't be a problem). Here is all of my code:

var c = $('.canvas');
var ctx = $(c)[0].getContext('2d');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id='canvas'>You're browser does not support the requirements to play this game. Update your browser or use a different browser</canvas>

I'm using Google and checking the console through F12, and it says -

Uncaught TypeError: Cannot read property 'getContext' of undefined

Any help is appreciated! Thanks!

Rojo
  • 2,749
  • 1
  • 13
  • 34

2 Answers2

1
  1. $(".canvas") selects all elements with a class of "canvas". You do not have any elements that satisfy this selector, as your <canvas> doesn't have any class on it at all.

    You could either use $("#canvas") to select by id, or $("canvas") to select by node type (<canvas>).

  2. var c is already a jQuery object - no need to re-wrap it in $(...)

  3. This is only a hunch based on your window.onload, but if your script is not at the end of the <body> or it's in the <head> but not wrapped in a $(document).ready( ... ), the code will look for the <canvas> element before it exists.

$(document).ready(function() {              // Remove this line if your code is at the end of <body>
    var $c = $('#canvas');
    var ctx = $c.get(0).getContext('2d');
});                                         // Remove this line if your code is at the end of <body>

I've changed var c to var $c and [0] to .get(0) strictly on the basis of personal preference.

Community
  • 1
  • 1
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
-1
$("#canvas")[0].getContext('2d');
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 1
    This answer could benefit from some sort of explanation, or at the very least you could acknowledge OP's error. – Tyler Roper Jan 24 '19 at 00:54
  • This is pretty much the same code I had, except for the fact you changed (c) to ('#canvas').... – Rojo Jan 24 '19 at 01:51