JavaScript - Canvas 不会显示图片

JavaScript - Canvas won't Show Image

这段代码只是用来显示我导入的图像,但我不知道为什么它不起作用。谢谢你的帮助。

var app = new FotoPrint();

function FotoPrint() {

this.init = function() {

    this.im = new Image();

    this.im.onload = function () {

        this.canvas = document.getElementById('canvas');
        this.ctx = this.canvas.getContext("2d");
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.strokeStyle = "black";
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.drawImage(this.im,0,0);

    };

    this.im.src = "Images/allison1.jpg";

};

};

app.init();

this 将在 onload 内改变。尝试设置一个变量,如:

var that = this;

this.im.onload 定义之前。

您可以在这里尝试:http://jsfiddle.net/8kv0px2m/

这是一个范围问题,这就是为什么我在解决这个问题时倾向于将我的变量命名为 scope(其他人使用 that,如另一个回答,或者别的,都无所谓。

所有这一切只是创建一个未在其他任何地方使用的新变量。与 this 不同,后者是引用当前范围内对象的特殊关键字。尝试使用控制台日志记录此代码,您应该会看到不同之处。 Outside onload 函数 this 指的是您的 FotoPrint 实例,而 inside onload 函数 this 指的是 img实例。

var app = new FotoPrint();

function FotoPrint() {

    var _scope_ = this;

    _scope_.init = function() {

        console.log('`this` outside onload', this);
        console.log('`_scope_` outside onload', _scope_);

        _scope_.im = new Image();
        _scope_.im.onload = function () {

            console.log('`this` inside onload', this);
            console.log('`_scope_` inside onload', _scope_);

            _scope_.canvas = document.getElementById('canvas');
            _scope_.ctx = _scope_.canvas.getContext("2d");
            _scope_.ctx.clearRect(0, 0, _scope_.canvas.width, _scope_.canvas.height);
            _scope_.ctx.strokeStyle = "black";
            _scope_.ctx.lineWidth = 2;
            _scope_.ctx.strokeRect(0, 0, _scope_.canvas.width, _scope_.canvas.height);
            _scope_.ctx.drawImage(_scope_.im,0,0);

        };

        _scope_.im.src = "Images/allison1.jpg";

    };

};

app.init();