【问题标题】:Uncaught TypeError: undefined is not a function with jQueryUncaught TypeError: undefined is not a function with jQuery
【发布时间】:2014-06-16 03:30:47
【问题描述】:

我正在学习 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);

【问题讨论】:

    标签: javascript jquery coffeescript


    【解决方案1】:

    不同之处在于 $('#myCanvas') 返回 jQuery 对象,而 document.getElementById('myCanvas') 返回 canvas html 元素。要获取画布上下文,您需要元素而不是对象。如果您想使用 jQuery,只需更改“canvas = $('#myCanvas');”到“canvas = $('#myCanvas')[0];”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 2014-08-15
      相关资源
      最近更新 更多