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);
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);
Share
Improve this question
asked Jun 15, 2014 at 19:26
H-HH-H
4561 gold badge9 silver badges16 bronze badges
1 Answer
Reset to default 10The 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];"