简体   繁体   中英

Uncaught TypeError: Cannot read property 'getContext' of undefined

I get this error "Uncaught TypeError: Cannot read property 'getContext' of undefined " while running script. It seems that variable "canvas" is undefined but I can't figure out why.

var world = {
    canvas: document.getElementById("myCanvas"),
    context: this.canvas.getContext("2d"),
    centerX: this.canvas.width / 2,
    centerY: this.canvas.height / 2,
    drawShape: function (shape) {
        if (typeof shape.draw() === "function")
            shape.draw();
    }
};

我在world文字之外声明了可变canvas ,它正在工作

An object literal doesn't establish a context for this , so you can't refer to an object as this within its literal definition.

In your case this.canvas.getContext is probably being evaluated as window.(undefined).getContext because window has no canvas property.

You can save a reference to the canvas property and avoid this :

var world = {
    canvas: (var canvas = document.getElementById("myCanvas")),
    context: canvas.getContext("2d"),
    centerX: canvas.width / 2,
    centerY: canvas.height / 2,
    drawShape: function (shape) {
        if (typeof shape.draw() === "function")
            shape.draw();
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM