getContext不是一个函数 [英] getContext is not a function

查看:1526
本文介绍了getContext不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用canvas来制作一个基本的web应用程序,当窗口调整大小时动态地更改画布大小。我已经得到它静态工作没有任何缺陷,但是当我创建一个对象使它动态,它在chrome中引发错误

I'm working on making a basic web application using canvas that dynamically changes the canvas size when the window resizes. I've gotten it to work statically without any flaws but when I create an object to make it dynamically it throws an error

错误是:


未捕获TypeError:Object [object Object]没有方法'getContext'

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

,在firefox中是:

and in firefox it is:


this.element.getContext不是函数

this.element.getContext is not a function

我在网上搜索,似乎是一个常见的问题,但没有一个修正提出任何区别。

I've searched the web and it seems like a common problem but none of the fixes mentioned make any difference.

代码有问题如下:

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());
}

提前感谢。

推荐答案

您的价值:

this.element = $(id);

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

is a jQuery object, not a pure Canvas element.

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

To turn it back so you can call getContext(), call this.element.get(0), or better yet store the real element and not the jQuery object:

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')
       .width(this.width)
       .height(this.height)
       .appendTo(location);

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

查看http://jsfiddle.net/alnitak/zbaMh/ ,最好使用Chrome JavaScript控制台,以便在调试输出中看到生成的对象。

See running code at http://jsfiddle.net/alnitak/zbaMh/, ideally using the Chrome Javascript Console so you can see the resulting object in the debug output.

这篇关于getContext不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆