Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: undefined is not a function with jQuery

I'm following a javascript/coffeescript/canvas tutorial, I have this javascript code:

(function() {
  $(function() {
    var canvas, context;
    console.log("DOM is ready");
    canvas = $('#myCanvas');
    context = canvas.getContext('2d');
    context.font = '40pt Calibri';
    context.fillStyle = 'blue';
    return context.fillText('Hello World!', 150, 100);
  });

}).call(this);

on calling canvas.getContext(), I'm getting an Uncaught TypeError: undefined is not a function.

If I replace canvas = $('#myCanvas'); with document.getElementById('myCanvas'); it works fine.

What do you think is the problem? Thank you!!

For info, this is my HTML:

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Demo</title>
    <script src="jquery-1.11.1.js"></script>
    <script src="test.js"></script>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>

And my original Coffeescript:

$ ->
    console.log("DOM is ready")
    canvas = document.getElementById('myCanvas');
    context = canvas.getContext('2d')
    context.font = '40pt Calibri';
    context.fillStyle = 'blue';
    context.fillText('Hello World!', 150, 100);
like image 861
H-H Avatar asked May 29 '26 21:05

H-H


1 Answers

The difference is that $('#myCanvas') returns jQuery object and document.getElementById('myCanvas') returns canvas html element. To get canvas context you need the element not an object. If you want use jQuery just change "canvas = $('#myCanvas');" to "canvas = $('#myCanvas')[0];"

like image 66
Vasiliy Gorokhov Avatar answered May 31 '26 11:05

Vasiliy Gorokhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!