Search code examples
node.jscanvasnode-canvas

Adding multiple images into a canvas


I'm trying to create a "banner" that has information on it, including images.

The banner looks like this:

enter image description here

An image would be placed on the circle and then text would be in the other areas.

My attempt fails, as an empty image is created.

const { createCanvas, loadImage } = require('canvas');
    const canvas = createCanvas(901, 231)
    const ctx = canvas.getContext('2d');
    const ctxAvatar = canvas.getContext('2d');
    const ctxSkin = canvas.getContext('2d');
    loadImage('assets/images/avatar.png').then(avatar => {
        ctxAvatar.drawImage(avatar, 50, 0, 70, 70);
        loadImage('assets/images/banner.png').then(banner => {
            ctx.drawImage(avatar, 50, 0, 70, 70);
            ctx.drawImage(banner, 50, 0, 70, 70);
        });
    });
    const output = canvas.toBuffer();

What am I doing wrong?


Solution

  • This should work:

    const canvas = createCanvas(901, 231)
    const ctx = canvas.getContext('2d');
    const ctxAvatar = canvas.getContext('2d');
    const ctxSkin = canvas.getContext('2d');
    loadImage('assets/images/avatar.png').then(avatar => {
        ctxAvatar.drawImage(avatar, 50, 0, 70, 70);
        loadImage('assets/images/banner.png').then(banner => {
            ctx.drawImage(banner, 50, 0, 70, 70);
            const output = canvas.toBuffer();
        });
    });
    

    The const output = canvas.toBuffer(); should be inside