我正在关注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()时,我得到了Uncaught TypeError: undefined is not a function.
如果我将canvas = $('#myCanvas');替换为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元素。要获取 Canvas 上下文,您需要的不是元素。如果要使用jQuery,只需更改“canvas = $('#myCanvas');”改为“ Canvas = $('#myCanvas')[0];”

10-08 01:07