I'm building a webapp that needs to display TIFF images in the browser (among other things) and am hitting a wall trying to properly organize the data.
I want to create a class that will hold the relevant data for the items I am working with so it can be used through class methods. Because the data is retrieved through parsing a TIFF file from a server, this needs to be accomplished through something like the Fetch API.
In the example below I am fetching a TIFF from a local URL using Chrome Web Server, then creating and displaying it in a canvas using Tiff.js (https://github.com/seikichi/tiff.js/tree/master):
class boardImage {
constructor(boardType) {
this.boardType = boardType;
this.boardURL = 'http://127.0.0.1:8887/28431413.Display.' + this.boardType + '.tif'
this.canvas;
this.width;
this.height;
this.loadImage()
}
async loadImage() {
fetch(this.boardURL)
.then((response) => {
response.arrayBuffer().then((buffer) => {
let tiff = new Tiff({buffer: buffer});
this.width = tiff.width();
this.height = tiff.height();
this.canvas = tiff.toCanvas();
if (this.canvas) {
this.canvas.classList.add("boardimage");
this.canvas.setAttribute('style', 'width:' + this.width + 'px; height: ' + this.height + 'px;');
// this works but I don't want to call this here
this.displayImage();
}
})
})
}
displayImage() {
document.getElementById("boardview").append(this.canvas);
}
}
The above code works because displayImage()
is called within the chain. When I call it outside of the chain the canvas images are undefined. In either situation the class members are set properly and I can see the appropriate values for canvas, width, and height in the browser console. I would like to just load the relevant data when I instantiate the class, and the call methods like displayImage()
or reference member variables when they need to be.
I understand that this is asynchronous behavior, but I don't know how to handle it properly. Thanks!