Search code examples
node.jscanvasaws-lambda

Unable to load Image with canvas.loadImage() via URL


Currently trying to upload an image via an URL in order to "draw" the image on top of the context (canvas). I am following the documentation here: https://www.npmjs.com/package/canvas and, cannot get any results from that function. Below is my code:

        const width = 1200
        const height = 600

        const canvas = createCanvas(width, height);
        const context = canvas.getContext('2d');

        context.fillStyle = '#000'
        context.fillRect(0, 0, width, height)

        context.font = 'bold 70pt Menlo'
        context.textAlign = 'center'
        context.textBaseline = 'top'
        context.fillStyle = '#3574d4'

        const text = 'Aj Diaz RE'

        const textWidth = context.measureText(text).width
        context.fillRect(600 - textWidth / 2 - 10, 170 - 5, textWidth + 20, 120)
        context.fillStyle = '#fff'
        context.fillText(text, 600, 170)

        context.fillStyle = '#fff'
        context.font = 'bold 30pt Menlo'
        context.fillText('johnrwood.com', 600, 530)

        const logo = loadImage('https://mystickermania.com/cdn/stickers/noob-pack/fallout-vault-boy-512x512.png');
        logo.then(() => {
            context.drawImage(logo, 340, 515, 70, 70)
            console.log("canvas.toDataURL('image/png')");
            console.log(canvas.toDataURL('image/png'));
            /*const buffer = canvas.toBuffer('image/png')
            console.log(buffer);*/
        }).catch(err => {
            console.log('oh no!', err)
        })

The function loadImage(), which uses logo.then() => doesn't seem to be doing anything.


Solution

  • After some research, moving the image processing to an async function did the trick.

    async function loadAndprocesslogoImage(context, imageURL){
    
       const imageLogo = await loadImage(imageURL);
       context.drawImage(imageLogo, 340, 515, 70, 70);
    
    }