I have this variable that saves the previous state of the canvas through getImageData(), however when I draw over it then try to revert back to the old state with putImageData() it doesn't work:
window.onload = async () => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let map;
const drawPicture = async (image) => {
const img = new Image();
img.src = `assets/${image}.png`;
img.onload = () => {
ctx.drawImage(img, 0, 0, 60, 60);
}
}
await drawPicture('log');
map = ctx.getImageData(0, 0, 60, 60);
await drawPicture('box');
await ctx.putImageData(map, 0, 0);
}
The culprit is the onload handler inside the drawPicture function. Simply marking a function as async using the async prefix isn't enough. In your case the function should wait until the image is loaded and draw it onto the canvas right after.
Written as it is right now, the onload handlers would fire sometime after your last function call :
await ctx.putImageData(map, 0, 0);
So the proper way is to let the function return a Promise, which is fulfilled as soon as the onload handler fires.
window.onload = async () => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let map;
const drawPicture = async (image) => {
return new Promise(resolve => {
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, 60, 60);
resolve();
}
img.src = `assets/${image}.png`;
});
}
await drawPicture('a');
map = ctx.getImageData(0, 0, 60, 60);
await drawPicture('b');
await ctx.putImageData(map, 0, 0);
}