惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
N
Netflix TechBlog - Medium
腾讯CDC
C
Check Point Blog
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
S
SegmentFault 最新的问题
F
Fortinet All Blogs
美团技术团队
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
F
Full Disclosure
Recorded Future
Recorded Future
D
DataBreaches.Net
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
J
Java Code Geeks
I
InfoQ
Y
Y Combinator Blog
A
About on SuperTechFans
AI
AI
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Forbes - Security
Forbes - Security
W
WeLiveSecurity
M
MIT News - Artificial intelligence
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
Schneier on Security
Schneier on Security
The GitHub Blog
The GitHub Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
Know Your Adversary
Know Your Adversary
Latest news
Latest news
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Docker
Recent Commits to openclaw:main
Recent Commits to openclaw:main
量子位
V2EX - 技术
V2EX - 技术
Project Zero
Project Zero

博客园 - 折翼的飞鸟

React中 state值根据props传入值变化的静态方法 getDerivedStateFromProps Taro4.x 引入 taro-ui 组件库 Taro4.x引入redux报错:TypeError: middleware is not a function uniapp+vue3 微信小程序使用mqtt通信 uniapp+vue3 在App.vue中如何设置全局调用方法 Taro 在页面中import包、组件、样式文件的顺序自定义规则 Taro优化VirtualList虚拟列表组件 Taro 引入moment.js打包过大 Taro 打包体积分析 React:消息订阅(subscribe)-发布(publish)机制 Taro 插件引入 Taro: chooseLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json Taro 支付宝小程序Page页获取小程序启动时的参数 Taro 主包vendors.js文件过大 Taro自定义Tabbar Taro 微信转支付宝小程序: 问题八 TypeError: Function(...) is not a function Taro微信转支付宝小程序:问题七 引入的文件图片文件名不能有@符号 Taro微信转支付宝小程序:问题六 同时编译微信小程序和支付宝小程序 Taro微信转支付宝小程序:问题五 编译时没有报错,工具中却莫名奇妙的错误提示
微信小程序分享图片显示自定义内容
折翼的飞鸟 · 2026-03-02 · via 博客园 - 折翼的飞鸟

小程序在分享页面增加了一个需求,就是要在分享的图片下面显示自定义的日期、星期、时间、识别,如下图:

image

要在小程序分享图片上显示时间日期(如你提供的示例图),核心思路是:先通过 Canvas 动态绘制包含时间的分享图,再将其作为自定义图片用于分享。下面以 Taro 框架为例,给出完整实现方案:

一、核心实现思路

  1. 准备画布:在页面中创建一个隐藏的 Canvas 组件,用于绘制分享图。
  2. 绘制内容:
    • 绘制背景图(如店铺招牌)。
    • 绘制半透明黑色背景条。
    • 在背景条上绘制白色的时间日期文字(如 “1 月 27 日 周四 19:00 晚餐”)。
  3. 生成图片:将绘制好的 Canvas 内容导出为临时图片文件。
  4. 自定义分享:在 onShareAppMessage 中,将生成的临时图片路径作为 imageUrl 返回,实现分享时显示自定义图片。

二、Taro 代码示例

  1. 页面配置

  在页面配置文件 page.config.js 中,开启分享功能:

export default {
  enableShareAppMessage: true,
}

  2. 页面结构与样式

  在页面中添加一个隐藏的 Canvas 组件:

import { Canvas, View } from '@tarojs/components'
import { useShareAppMessage, createCanvasContext, canvasToTempFilePath, downloadFile } from '@tarojs/taro'

export default function SharePage() {
  // 预订时间
  const bookTime = '1月27日 周四 19:00 晚餐'
  // 网络背景图地址(替换为你的实际地址)
  const bgImageUrl = 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/e718ea1f4e8a44e8bb7e64516b08d215.png'

  // 下载网络图片到本地
  const downloadImage = async (url) => {
    try {
      const res = await downloadFile({
        url: url, // 网络图片地址
        // header: {
          // 部分图片需要设置请求头(如防盗链),根据实际情况添加
          // 'Referer': 'https://xxx.com' // 示例:设置referer
        // }
      })
      // 下载成功返回临时文件路径
      if (res.statusCode === 200) {
        return res.tempFilePath
      } else {
        throw new Error('图片下载失败')
      }
    } catch (error) {
      console.error('下载图片出错:', error)
      // 下载失败时使用本地默认图兜底
      return '/assets/images/default-bg.jpg'
    }
  }

  // 生成分享图
  const generateShareImage = async () => {
    return new Promise(async (resolve, reject) => {
      // 1. 先下载网络图片到本地
      const bgImagePath = await downloadImage(bgImageUrl)

      // 2. 获取Canvas上下文
      const ctx = createCanvasContext('shareCanvas')

      // 3. 绘制背景图(使用下载后的临时路径)
      ctx.drawImage(bgImagePath, 0, 0, 375, 250) // Canvas尺寸375x250

      // 4. 绘制半透明黑色背景条
      ctx.setFillStyle('rgba(0, 0, 0, 0.5)')
      ctx.fillRect(0, 200, 375, 50)

      // 5. 绘制时间文字
      ctx.setFillStyle('#ffffff')
      ctx.setFontSize(16)
      ctx.fillText(bookTime, 20, 230)

      // 6. 绘制完成后导出为图片
      ctx.draw(false, () => {
        canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success: (res) => {
            resolve(res.tempFilePath)
          },
          fail: reject
        })
      })
    })
  }

  // 7. 配置分享 如果使用onShareAppMessage 方法也可以使用 onShareAppMessage = async (obj) => {...}
  useShareAppMessage(async () => {
    const imageUrl = await generateShareImage(); // 创建分享图片路径
    return {
      title: '贵宾王董事长先生您好,这是您的预订回执',
      path: '/pages/share/share',
      imageUrl: imageUrl
    }
  })return (
    <View>
      {/* 隐藏的Canvas */}
      <Canvas canvasId="shareCanvas" style={{ position: 'absolute', left: '-9999px', width: '375px', height: '250px' }} />
    {/* 显示其他组件内容 */}
    <View> ... </View> </View> ) }

在 Canvas 中绘制背景图时能否直接使用网络图片路径,答案是:不可以直接使用,小程序的 Canvas drawImage 方法对网络图片有严格限制,直接使用会绘制失败。

 核心原因

  小程序出于安全和性能考虑,drawImage 方法仅支持以下类型的图片路径:

  1. 本地资源路径(如 /assets/images/xxx.jpg
  2. 临时文件路径(通过 wx.downloadFile 下载后的路径)
  3. 代码包路径(/pages/xxx/xxx.png
  4. 本地缓存路径(wxfile:// 开头)

  直接使用 https://xxx.com/xxx.jpg 这类网络路径,Canvas 会无法识别,导致背景图绘制不出来。

 解决方案:先下载网络图片到本地

  核心思路是:先用 wx.downloadFile(Taro 中为 downloadFile)将网络图片下载到本地,获取临时文件路径,再用这个路径绘制到 Canvas 上。

 额外注意事项

  1. 配置 downloadFile 域名白名单:
    小程序后台需要在「开发管理 - 开发设置 - 服务器域名」中,将图片域名添加到 downloadFile 合法域名列表,否则下载会失败。分享图片就是空白
  2. 图片防盗链处理:
    部分网站的图片有防盗链限制,此时需要在 downloadFileheader 中添加 Referer(值为图片所属域名),或者让后端处理图片转发。
  3. 错误兜底:
    一定要添加下载失败的兜底逻辑(比如使用本地默认图),避免分享功能完全失效。  
  4. 配置downloadFile合法域名:
    image

 总结

  1. Canvas 绘制背景图不能直接用网络路径,必须先通过 downloadFile 下载到本地获取临时路径;
  2. 关键步骤:下载网络图片 → 获取临时路径 → 用临时路径绘制 Canvas;
  3. 必须在小程序后台配置下载域名白名单,否则会触发跨域限制。

三、关键注意事项

  1. 图片路径drawImage 方法在小程序中对网络图片支持有限,建议先将网络图片下载到本地,再使用本地路径绘制。
  2. Canvas 尺寸:分享图片的推荐比例为 5:4,Canvas 尺寸应与此比例一致,避免图片变形。
  3. 异步处理:生成图片和分享都是异步操作,useShareAppMessage 必须返回一个 Promise 来等待图片生成完成。
  4. 兼容性:不同端(微信、支付宝等)的 Canvas API 可能存在差异,需要根据目标平台进行适配。