gpt4 book ai didi

javascript - Angular 4 : TypeError: this. 函数不是函数

转载 作者:行者123 更新时间:2023-12-03 01:44:44 25 4
gpt4 key购买 nike

我没有主意了..我看到这个问题被问了很多次 herehere还有更多,但我找不到解决我的问题的方法。据我了解,问题是 this 它没有引用正确的上下文。如何使用箭头函数从声明站点捕获this

drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {
// more code than displayed here
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}

onFileSelected(event) {
for (const file of event.target.files) {
if (file) {
const reader = new FileReader();

reader.onload = function(e: FileReaderEvent) {
const canvas = <HTMLCanvasElement>document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image;

img.onload = draw;

function draw() {
this.drawImageProp(ctx, this, 0, 0, canvas.width, canvas.height, 0.5, 0.5);
}

img.src = e.target.result;
};

reader.readAsDataURL(file);
}
}
}

最佳答案

使用闭包:

onFileSelected(event) {
const self = this;
for (const file of event.target.files) {
if (file) {
const reader = new FileReader();

reader.onload = function(e: FileReaderEvent) {
const canvas = <HTMLCanvasElement>document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image;

img.onload = draw;

function draw() {
self.drawImageProp(ctx, img, 0, 0, canvas.width, canvas.height, 0.5, 0.5);
}

img.src = e.target.result;
};

reader.readAsDataURL(file);
}
}
}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com