Help! I'm trying to combine images using canvas but the output always comes out as a blank box. I can't figure out what is going wrong, my code is below:
const Canvas = require('canvas'); const theLayers=['https://raw.githubusercontent.com/Iceee1000/SpaceVizsla/main/MediaAssets/pixelVizsla/testing_01.png', 'https://raw.githubusercontent.com/Iceee1000/SpaceVizsla/main/MediaAssets/pixelVizsla/B_02.png', 'https://raw.githubusercontent.com/Iceee1000/SpaceVizsla/main/MediaAssets/pixelVizsla/testing_02.png']; //not-working function to combine multiple layers of images from the web. const CombineLayers = async(layers) => { console.log('combining layers') let canvas=Canvas.createCanvas(250, 250); let context=canvas.getContext('2d'); for (let layer of layers){ var img = new Image(); img.origin = 'anonymous'; img.src = layer; img.onload = function(){ context.drawImage(img, 0, 0, 250, 250); } } return canvas.toDataURL("image/png"); }; const dothings=async()=>{ const result= await CombineLayers(theLayers); console.log(result); } dothings();
drawImageoverwrites the existing canvas.canvas.toDataURL("image/png"). See Loading images before rendering JS canvas