我正在关注javascript / coffeescript / canvas教程,我有这个javascript代码:
(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);
在调用canvas.getContext()时,我得到一个未捕获的TypeError:undefined不是一个函数.
如果我替换canvas = $(‘#myCanvas’); with document.getElementById(‘myCanvas’);它工作正常.
您认为这个问题是什么?谢谢!!
有关信息,这是我的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>
而我原来的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);
解决方法:
区别在于$(‘#myCanvas’)返回jQuery对象而document.getElementById(‘myCanvas’)返回canvas html元素.要获取画布上下文,您需要元素而不是对象.如果你想使用jQuery只需更改“canvas = $(‘#myCanvas’);” to“canvas = $(‘#myCanvas’)[0];”