I have an GIF.js object in my this object which I would like to this.gif.addframe(mapcanvas) in a loop that goes through a date array at the end of which I this.gif.render(). I must make use of this inside the callback which I understand would be possible if I were to cache it and use an arrow function but I need to have something like
for(let i = 0 ; i < this.dateArraySurface10.length-2 ; i++)
{
this.setTimeSurface10();
this.map.renderSync();
var self = this;
const mapCanvas = document.createElement('canvas');
this.map.once('rendercomplete', function () {
const divElement = document.querySelector(".map");
mapCanvas.width = divElement.offsetWidth;//size[0];
mapCanvas.height = divElement.offsetHeight;//size[1];
const mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(
document.querySelectorAll('.ol-layer canvas'),
function (canvas) {
if (canvas.width > 0) {
const opacity = canvas.parentNode.style.opacity;
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
const transform = canvas.style.transform;
const matrix = transform
.match(/^matrix\(([^\(]*)\)$/)[1] //eslint-disable-line
.split(',')
.map(Number);
CanvasRenderingContext2D.prototype.setTransform.apply(
mapContext,
matrix
);
mapContext.drawImage(canvas, 0, 0);
}
}
);
self.gif.addFrame(mapCanvas, {copy:true, delay: 200});
console.log(i);
});
}
this.gif.on('finished', function(blob) {
window.open(URL.createObjectURL(blob));
});
this.gif.render();
}
where
setTimeSurface10: function () {
if (this.currentTimeSurface10 === null) {
this.currentTimeSurface10 = this.startTimeSurface10;
} else if (this.currentTimeSurface10 >= this.endTimeSurface10) {
this.currentTimeSurface10 = this.startTimeSurface10;
} else {
this.currentTimeSurface10 = new Date(
this.currentTimeSurface10.setMinutes(
this.currentTimeSurface10.getMinutes() + 60)
);
}
this.surface10.getSource().updateParams({ TIME:
this.currentTimeSurface10.toISOString().split(".")[0] + "Z" });
}
This is nothing but pseudo code since for the moment I managed to produce a very boring GIF that adds the same frame over and over again using the let vm = this and arrow function pattern. Can someone explain to me how I am to access and use this inside my callback inside my loop?
this inside the callback is the map object. If you cannot use arrow functions (e.g. you must support old browsers) assign a variable to this before setting the listener
for(date in dateArray) {
this.map.setTime(date)
var self = this;
this.map.on('renderComplete', function() {
self.gif.addFrame(mapcanvas)
}
}
this.gif.render()