我正在使用 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/