javascript - getContext 不是函数

标签 javascript jquery html canvas

我正在使用 Canvas 制作一个基本的 Web 应用程序,它会在窗口调整大小时动态更改 Canvas 大小。我已经让它静态地工作,没有任何缺陷,但是当我创建一个对象使其动态地工作时,它会抛出一个错误

在 chrome 中错误是:

Uncaught TypeError: Object [object Object] has no method 'getContext'

在 firefox 中是:

this.element.getContext is not a function

我在网上搜索了一下,这似乎是一个常见问题,但提到的所有修复都没有任何区别。

问题代码如下:

layer['background'] = new canvasLayer("body","background");
function canvasLayer(location,id){
    $(location).append("<canvas id='"+id+"'>unsupported browser</canvas>");
    this.element=$(id);
    this.context = this.element.getContext("2d"); //this is the line that throws the error
    this.width=$(window).width(); //change the canvas size
    this.height=$(window).height();
    $(id).width($(window).width()); //change the canvas tag size to maintain proper scale
    $(id).height($(window).height());
}

提前致谢。

最佳答案

你的值(value):

this.element = $(id);

是一个 jQuery 对象,不是纯 Canvas 元素。

将其返回以便您可以调用 getContext()、调用 this.element.get(0),或者更好的是存储真实元素而不是 jQuery对象:

function canvasLayer(location, id) {

    this.width = $(window).width();
    this.height = $(window).height();
    this.element = document.createElement('canvas');

    $(this.element)
       .attr('id', id)
       .text('unsupported browser')
       .attr('width', this.width)       // for pixels
       .attr('height', this.height)
       .width(this.width)               // for CSS scaling
       .height(this.height)
       .appendTo(location);

    this.context = this.element.getContext("2d");
}

查看运行代码 http://jsfiddle.net/alnitak/zbaMh/ ,最好使用 Chrome Javascript 控制台,这样您就可以在调试输出中看到生成的对象。

关于javascript - getContext 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5808162/

相关文章:

javascript - PebbleJS 中的日期格式化和操作

javascript - $(document).ready() 中的函数未找到 DOM 的 body 元素

html - 当第二行使用 span 元素时,对齐两行文本的正确 html 代码是什么?

javascript - 在样式元素上使用 title 属性时出现问题

javascript - 将 SQLite PHP 数组转换为 Javascript 数组?

javascript - Vue 3 : Emit event from child to parent

javascript - 修改正则表达式以获得最大长度

asp.net-mvc - jQuery.Load() 不触发 ASP.NET MVC2 中的 Request.IsAjaxRequest

javascript - JQuery - 复制元素的尺寸和绝对位置

javascript - 使用 Jquery 防止在 html() 期间创建 html 标签