Search code examples
discorddiscord.jsnode-canvas

discord.js canvas image manipulation


I wan't to make a command that put the user avatar in my wanted image

    const { createCanvas, loadImage } = require('canvas')
    const { MessageAttachment } = require('discord.js');
    const Command = require('../../structures/Command')

    module.exports = class extends Command {
        constructor(client) {
            super(client, {
                name: 'wanted',
                description: 'Coloca a cabeça de um usuário valendo $2000.',
                options: [
                    {
                        name: 'user',
                        description: 'Usuário que terá a cabeça posta num cartaz de procurado',
                        type: 'USER',
                        required: true
                    }
                ]
            })
        }

        run = async (interaction) => {
            const canvas = createCanvas(239, 338)
            const ctx = canvas.getContext('2d')
            const wantedImg = await loadImage("imgs/wanted.png")
            const userAv = interaction.options.getUser('user')
            const Avatar = userAv.avatarURL()
            interaction.reply(wantedImg)
        }
    }

I put the wantedImg in interaction.reply to see if the client return in chat the wanted image, but it's getting error...

Cannot find module 'C:\Users\pulse\OneDrive\Documentos\Cynthia\JS\src\commands\imgs\imgs'


Solution

  • I would recommend using jimp instead:

    const user = message.mentions.users.first() //get The first user mentioned
    if (!user) return message.reply("Who is wanted?")//return if no user was mentioned
    
    var wantedImage = "wanted image url goes here"
    var pfp = user.avatarURL({ format: 'png', dynamic: true, size: 128 }) //Get link of profile picture
    var image = await Jimp.read(pfp)//read the profile picture, returns a Jimp object
    
    //Composite resized bars on profile picture
    image.composite((await Jimp.read(bars)).resize(128, 128), 0, 0)
    
    //Create and attachment using buffer from edited picture and sending it
    var image = new Discord.MessageAttachment(await image.getBufferAsync(Jimp.MIME_PNG))
    
    message.reply(image) //replies to original command with image
    

    It has far more options than canvas.