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

如何使用Node.js生成带中心Logo的二维码

后端生成带Logo二维码的实现方案

方案一:配置canvas环境使用qrcode-with-logos

qrcode-with-logos依赖canvas,在Node.js后端需要先安装canvas的系统依赖(以Ubuntu为例):

sudo apt-get install libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev build-essential g++

然后安装npm包:

npm install qrcode-with-logos

接下来写后端API代码(以Express为例),生成带Logo的二维码并返回:

const express = require('express');
const QRCodeWithLogos = require('qrcode-with-logos');
const app = express();

app.get('/qrcode-with-logo', async (req, res) => {
  try {
    const qrBuffer = await QRCodeWithLogos.toBuffer({
      text: 'https://example.com', // 二维码内容
      width: 300,
      logo: './path/to/your/logo.png', // Logo本地路径
      logoWidth: 60, // Logo宽度建议为二维码的1/5左右,避免遮挡识别
      logoHeight: 60,
      margin: 10
    });
    res.setHeader('Content-Type', 'image/png');
    res.send(qrBuffer);
  } catch (err) {
    res.status(500).send('生成二维码失败:' + err.message);
  }
});

app.listen(3000, () => console.log('服务已启动'));

方案二:手动合并SVG二维码与Logo(无需canvas)

如果你已经用qrcode生成SVG,可以直接操作SVG DOM插入Logo,完全避免canvas依赖:

  1. 先用qrcode生成基础SVG字符串:
const QRCode = require('qrcode');
const svgString = await QRCode.toString('https://example.com', { type: 'svg', width: 300 });
  1. 用cheerio解析并修改SVG,插入Logo元素(支持SVG格式Logo或PNG图片):
    先安装依赖:
npm install cheerio

然后编写合并逻辑:

const cheerio = require('cheerio');

const $ = cheerio.load(svgString, { xmlMode: true });
const svgWidth = parseInt($('svg').attr('width'));
const svgHeight = parseInt($('svg').attr('height'));
const logoSize = 60;
// 计算Logo居中位置
const logoX = (svgWidth - logoSize) / 2;
const logoY = (svgHeight - logoSize) / 2;

// 先加白色背景块避免Logo与二维码色块重叠,再插入Logo
$('svg').append(`
  <g>
    <rect x="${logoX - 5}" y="${logoY - 5}" width="${logoSize + 10}" height="${logoSize + 10}" fill="white" />
    <!-- 若为PNG Logo,替换为<image xlink:href="./path/to/logo.png" x="${logoX}" y="${logoY}" width="${logoSize}" height="${logoSize}" /> -->
    <svg x="${logoX}" y="${logoY}" width="${logoSize}" height="${logoSize}" viewBox="0 0 100 100">
      <!-- 这里替换为你的Logo SVG代码 -->
      <circle cx="50" cy="50" r="40" fill="#2563eb" />
    </svg>
  </g>
`);

const finalSvg = $.xml();
res.setHeader('Content-Type', 'image/svg+xml');
res.send(finalSvg);

这种方法更轻量,适合已有SVG生成流程的场景。

内容的提问来源于stack exchange,提问作者Terra Tor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:30:15