You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js结合canvas与merge-images报sources.map非函数TypeError错误

错误根因

merge-images模块的第一个入参必须为数组格式的图片源列表,当前代码直接传入单个文件路径字符串,模块内部尝试对该字符串调用.map()方法时触发类型错误。

修复方式

将单张图片路径包裹为数组即可解决报错,若后续需要合并多张图片,只需在数组中继续追加图片路径、base64编码或图片对象即可。

修复后的完整代码
const mergeImages = require('merge-images')
const { Canvas, Image } = require('canvas');
const Discord = require('discord.js')
module.exports = {
    name: 'avatar',
    description: 'avatar',
    async execute(message, args) {               
        // 单张图片也需包裹为数组传入
        let b64 = await mergeImages(['assets/colors/yellow.png'], { Canvas: Canvas, Image: Image });
        b64 = b64.split(';base64,').pop();
        await message.channel.send({ files: [{ attachment: Buffer.from(b64, 'base64'), name: `avatar.png` }] });
    }
}
补充校验项
  • 确认assets/colors/yellow.png的相对路径相对于你的项目启动文件(即运行Discord bot的入口js)可被正常读取,若运行时提示找不到文件,可引入path模块将相对路径转换为基于当前文件的绝对路径,比如path.join(__dirname, '../assets/colors/yellow.png'),避免运行目录变动导致的路径解析异常
  • 若需要叠加用户头像等远程资源,直接将图片URL加入数组即可被模块自动加载处理
  • 若需要控制不同图片的叠加位置,可将数组内的项改为对象格式,例如{ src: 'assets/colors/yellow.png', x: 0, y: 0 },自定义每张图的摆放坐标

内容的提问来源于stack exchange,提问作者Meme Loke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.26 14:45:02