Reputation: 953
I run out of ideas.. I saw this question got asked many times here and here and many more, but I could not find a way to solve my issue. So as I understood, the problem is this
it does not refer to the correct context. How do I use an arrow function to capture this
from the declaration site?
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);
}
}
}
Upvotes: 0
Views: 3003
Reputation: 11982
Use a closure:
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);
}
}
}
Upvotes: 1