I am looping and combining images, but I simply get a blank canvas. Here is my code:
const canvas = createCanvas(1024, 1024);
const numberOfSquares = Math.sqrt(imageFiles.length);
const size = 1024 / numberOfSquares;
var currentX = 0;
var currentY = 0;
for (let h = 0; h < numberOfSquares; h++) {
for (let i = 0; i < numberOfSquares; i++) {
loadImage('./images/0.png').then((image) => {
ctx.drawImage(image, currentX, currentY, size, size);
currentX += size;
});
if (h === 9 && i === 9) {
console.log(canvas.toDataURL());
// hardcoded value for testing
}
currentX += size;
}
currentX = 0;
currentY += size;
}
There are two problems
- The canavas gets logged before the loop has completed
- When I log
currentX
andcurrentY
I simply get
102.4 1023.9999999999999
204.8 1023.9999999999999
307.20000000000005 1023.9999999999999
409.6 1023.9999999999999
512 1023.9999999999999
614.4 1023.9999999999999
716.8 1023.9999999999999
819.1999999999999 1023.9999999999999
...
Note: when I test it with stroke, beginPath, rect etc it works fine
EDIT
See comments for answer
Here's the updated code btw
const canvas = createCanvas(1024, 1024);
const numberOfSquares = Math.sqrt(imageFiles.length);
const size = 1024 / numberOfSquares;
var currentX = 0;
var currentY = 0;
for (let h = 0; h < numberOfSquares; h++) {
for (let i = 0; i < numberOfSquares; i++) {
const image = await loadImage('./images/0.png');
const ctx = canvas.getContext('2d');
ctx.drawImage(image, currentX, currentY, size, size);
currentX += size;
if (h === 9 && i === 9) {
console.log(canvas.toDataURL());
}
}
currentX = 0;
currentY += size;