poster.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /**
  2. * 名片海报生成工具
  3. * 使用 Canvas 2D 绘制名片海报
  4. * 名片底部添加名片码(二维码)
  5. */
  6. const W = 750
  7. const H = 600
  8. const PADDING = 40
  9. const roundRect = (ctx, x, y, w, h, r) => {
  10. ctx.beginPath()
  11. ctx.moveTo(x + r, y)
  12. ctx.lineTo(x + w - r, y)
  13. ctx.quadraticCurveTo(x + w, y, x + w, y + r)
  14. ctx.lineTo(x + w, y + h - r)
  15. ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h)
  16. ctx.lineTo(x + r, y + h)
  17. ctx.quadraticCurveTo(x, y + h, x, y + h - r)
  18. ctx.lineTo(x, y + r)
  19. ctx.quadraticCurveTo(x, y, x + r, y)
  20. ctx.closePath()
  21. }
  22. /**
  23. * 创建图片对象 - 必须使用 canvas.createImage()
  24. * 微信小程序 Canvas 2D 中不能用 uni.createImage()
  25. */
  26. const createCanvasImage = (canvas, src) => {
  27. return new Promise((resolve) => {
  28. if (!src || !canvas) return resolve(null)
  29. const img = canvas.createImage()
  30. img.onload = () => resolve(img)
  31. img.onerror = () => {
  32. console.warn('图片加载失败:', src)
  33. resolve(null)
  34. }
  35. img.src = src
  36. })
  37. }
  38. const downloadImage = async (url) => {
  39. try {
  40. if (!url || !url.startsWith('http')) return url
  41. // 使用 getImageInfo 获取图片本地临时路径(微信原生能力,通过 request 域名即可,无需 downloadFile 白名单)
  42. const res = await uni.getImageInfo({ src: url })
  43. if (res && res.path) return res.path
  44. return null
  45. } catch (e) {
  46. console.warn('获取图片信息失败:', url, e)
  47. return null
  48. }
  49. }
  50. /**
  51. * 将图片资源转换为Canvas可用的临时路径
  52. */
  53. const resolveImageSrc = async (src) => {
  54. if (!src) return null
  55. if (src.startsWith('http')) {
  56. try {
  57. // getImageInfo 走 request 域名,无需额外配置 downloadFile 白名单
  58. const res = await uni.getImageInfo({ src })
  59. if (res && res.path) return res.path
  60. return null
  61. } catch { return null }
  62. }
  63. if (src.startsWith('/') || src.startsWith('.')) {
  64. try {
  65. const res = await uni.getImageInfo({ src })
  66. return res.path
  67. } catch { return null }
  68. }
  69. return src
  70. }
  71. /**
  72. * base64 二维码转临时文件路径
  73. */
  74. const qrBase64ToTempFile = async (base64Data) => {
  75. if (!base64Data) return null
  76. return new Promise((resolve) => {
  77. try {
  78. const pureBase64 = base64Data.replace(/^data:image\/\w+;base64,/, '')
  79. const fileName = `${Date.now()}_qrcode.png`
  80. const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
  81. const fs = uni.getFileSystemManager()
  82. fs.writeFile({
  83. filePath,
  84. data: pureBase64,
  85. encoding: 'base64',
  86. success: () => resolve(filePath),
  87. fail: () => resolve(null)
  88. })
  89. } catch {
  90. resolve(null)
  91. }
  92. })
  93. }
  94. const drawCircleAvatar = (ctx, img, cx, cy, r) => {
  95. ctx.save()
  96. ctx.beginPath()
  97. ctx.arc(cx, cy, r, 0, Math.PI * 2)
  98. ctx.clip()
  99. if (img) ctx.drawImage(img, cx - r, cy - r, r * 2, r * 2)
  100. ctx.restore()
  101. }
  102. const drawAvatarFallback = (ctx, cardInfo, cx, cy, r) => {
  103. ctx.save()
  104. ctx.beginPath()
  105. ctx.arc(cx, cy, r, 0, Math.PI * 2)
  106. ctx.fillStyle = '#4080FF'
  107. ctx.fill()
  108. ctx.strokeStyle = 'rgba(255,255,255,0.6)'
  109. ctx.lineWidth = 4
  110. ctx.stroke()
  111. const initial = cardInfo.nickName ? cardInfo.nickName.charAt(0) : '?'
  112. ctx.fillStyle = '#FFFFFF'
  113. ctx.font = `bold ${r}px sans-serif`
  114. ctx.textAlign = 'center'
  115. ctx.textBaseline = 'middle'
  116. ctx.fillText(initial, cx, cy)
  117. ctx.restore()
  118. }
  119. const drawContactRow = (ctx, iconImg, text, x, y) => {
  120. if (!text) return
  121. // 图标(40x40)
  122. const iconSize = 32
  123. const iconX = x
  124. const iconY = y
  125. if (iconImg) {
  126. ctx.drawImage(iconImg, iconX, iconY, iconSize, iconSize)
  127. }
  128. ctx.font = '26px sans-serif'
  129. ctx.textAlign = 'left'
  130. ctx.textBaseline = 'middle'
  131. ctx.fillStyle = '#202020'
  132. const textMaxWidth = 480
  133. const textX = x + iconSize + 12
  134. if (ctx.measureText(text).width > textMaxWidth) {
  135. ctx.textBaseline = 'top'
  136. const lineY = y + 4
  137. fillTextWrap(ctx, text, textX, lineY, textMaxWidth, 40, 'left')
  138. } else {
  139. ctx.fillText(text, textX, y + iconSize / 2)
  140. }
  141. }
  142. const fillTextWrap = (ctx, text, x, y, maxWidth, lineHeight, align = 'left') => {
  143. if (!text) return y
  144. ctx.textAlign = align
  145. ctx.textBaseline = 'top'
  146. const chars = text.split('')
  147. let line = '', cy = y
  148. for (let i = 0; i < chars.length; i++) {
  149. const test = line + chars[i]
  150. if (ctx.measureText(test).width > maxWidth && i > 0) {
  151. ctx.fillText(line, x, cy)
  152. line = chars[i]
  153. cy += lineHeight
  154. } else {
  155. line = test
  156. }
  157. }
  158. ctx.fillText(line, x, cy)
  159. return cy + lineHeight
  160. }
  161. export const generateCardPoster = async (cardInfo = {}, qrInfo = {}) => {
  162. return new Promise((resolve, reject) => {
  163. const query = uni.createSelectorQuery()
  164. query.select('#posterCanvas')
  165. .fields({ node: true, size: true })
  166. .exec(async (res) => {
  167. if (!res || !res[0]) {
  168. reject(new Error('Canvas 节点未找到'))
  169. return
  170. }
  171. const canvas = res[0].node
  172. const ctx = canvas.getContext('2d')
  173. const dpr = uni.getSystemInfoSync().pixelRatio || 2
  174. canvas.width = W * dpr
  175. canvas.height = H * dpr
  176. ctx.scale(dpr, dpr)
  177. // ===== 1. 渐变背景 =====
  178. const bgGrad = ctx.createLinearGradient(0, 0, 0, H)
  179. bgGrad.addColorStop(0, '#155DFC')
  180. bgGrad.addColorStop(0.5, '#155DFC')
  181. bgGrad.addColorStop(1, '#155DFC')
  182. ctx.fillStyle = bgGrad
  183. ctx.fillRect(0, 0, W, H)
  184. // ===== 2. 装饰圆点 =====
  185. ctx.fillStyle = 'rgba(255,255,255,0.10)'
  186. ctx.beginPath(); ctx.arc(620, 160, 100, 0, Math.PI * 2); ctx.fill()
  187. ctx.beginPath(); ctx.arc(680, 320, 60, 0, Math.PI * 2); ctx.fill()
  188. ctx.beginPath(); ctx.arc(-20, 640, 80, 0, Math.PI * 2); ctx.fill()
  189. // ===== 3. 白色卡片(去掉白色背景,只保留圆角裁剪区域)=====
  190. const cardX = 20, cardY = 60
  191. const cardW = W - 40, cardH = 480
  192. const innerPad = 16
  193. const innerX = cardX + innerPad
  194. const innerY = cardY + innerPad
  195. const innerW = cardW - innerPad * 2
  196. const innerH = cardH - innerPad * 2
  197. // 背景图(静态资源直接传路径,canvas.createImage 支持加载本地包内资源)
  198. try {
  199. const cardBg = await createCanvasImage(canvas, '/static/image/home/usecard-bg.png')
  200. if (cardBg) {
  201. ctx.save()
  202. roundRect(ctx, innerX, innerY, innerW, innerH, 16)
  203. ctx.clip()
  204. ctx.drawImage(cardBg, innerX, innerY, innerW, innerH)
  205. ctx.restore()
  206. }
  207. } catch (e) {
  208. console.warn('加载名片背景图失败:', e)
  209. }
  210. // ===== 5. 头像(右上角)=====
  211. const avatarCx = innerX + innerW - 100
  212. const avatarCy = innerY + 115
  213. const avatarR = 60
  214. ctx.save()
  215. ctx.beginPath()
  216. ctx.arc(avatarCx, avatarCy, avatarR + 4, 0, Math.PI * 2)
  217. ctx.fillStyle = 'rgba(255,255,255,0.5)'
  218. ctx.fill()
  219. ctx.restore()
  220. let avatarImg = null
  221. if (cardInfo.avatar) {
  222. // 先用 downloadImage(内部走 getImageInfo)获取本地临时路径
  223. const localPath = await downloadImage(cardInfo.avatar)
  224. if (localPath) {
  225. avatarImg = await createCanvasImage(canvas, localPath)
  226. } else {
  227. console.warn('未能获取头像本地路径,直接尝试原始链接')
  228. }
  229. }
  230. if (avatarImg) {
  231. drawCircleAvatar(ctx, avatarImg, avatarCx, avatarCy, avatarR)
  232. } else {
  233. drawAvatarFallback(ctx, cardInfo, avatarCx, avatarCy, avatarR)
  234. }
  235. // ===== 6. 姓名 + 职位 + 公司 =====
  236. const nameX = innerX + 44
  237. const nameY = innerY + 70
  238. ctx.fillStyle = '#202020'
  239. ctx.font = 'bold 44px sans-serif'
  240. ctx.textAlign = 'left'
  241. ctx.textBaseline = 'top'
  242. const name = cardInfo.nickName || '用户'
  243. ctx.fillText(name, nameX, nameY)
  244. const nameW = ctx.measureText(name).width
  245. if (cardInfo.postName) {
  246. ctx.font = '22px sans-serif'
  247. ctx.fillStyle = '#202020'
  248. ctx.textAlign = 'left'
  249. ctx.textBaseline = 'top'
  250. ctx.fillText(cardInfo.postName, nameX + nameW + 14, nameY + 11)
  251. }
  252. // 公司名称
  253. ctx.fillStyle = '#202020'
  254. ctx.font = '26px sans-serif'
  255. ctx.textAlign = 'left'
  256. ctx.textBaseline = 'top'
  257. const companyMaxW = innerW - 200
  258. const companyName = cardInfo.companyName || '公司名称'
  259. const companyX = innerX + 44
  260. const companyY = nameY + 60
  261. const companyEndY = fillTextWrap(ctx, companyName, companyX, companyY, companyMaxW, 36, 'left')
  262. // ===== 7. 联系方式 =====
  263. const contactY = Math.max(companyEndY + 24, innerY + 160)
  264. const contactX = innerX + 44
  265. const contactGap = 60
  266. // 预加载联系方式图标
  267. const phoneIcon = await createCanvasImage(canvas, '/static/image/public/phone-icon.png')
  268. const emailIcon = await createCanvasImage(canvas, '/static/image/public/email-icon.png')
  269. const addressIcon = await createCanvasImage(canvas, '/static/image/public/address-icon.png')
  270. drawContactRow(ctx, phoneIcon, cardInfo.phonenumber, contactX, contactY + 20)
  271. drawContactRow(ctx, emailIcon, cardInfo.email, contactX, contactY + 20 + contactGap)
  272. drawContactRow(ctx, addressIcon, cardInfo.companyAddress, contactX, contactY + 20 + contactGap * 2)
  273. // ===== 8. 导出 =====
  274. setTimeout(() => {
  275. uni.canvasToTempFilePath({
  276. canvas,
  277. success: (res) => resolve(res.tempFilePath),
  278. fail: (err) => reject(err)
  279. })
  280. }, 600)
  281. })
  282. })
  283. }
  284. export const savePosterToAlbum = (tempFilePath) => {
  285. return new Promise((resolve, reject) => {
  286. uni.authorize({
  287. scope: 'scope.writePhotosAlbum',
  288. success: () => {
  289. uni.saveImageToPhotosAlbum({
  290. filePath: tempFilePath,
  291. success: () => resolve(),
  292. fail: (err) => reject(err)
  293. })
  294. },
  295. fail: () => {
  296. uni.showModal({
  297. title: '提示',
  298. content: '需要授权相册权限才能保存名片',
  299. confirmText: '去设置',
  300. success: (res) => {
  301. if (res.confirm) uni.openSetting({})
  302. reject(new Error('未授权'))
  303. }
  304. })
  305. }
  306. })
  307. })
  308. }
  309. export default { generateCardPoster, savePosterToAlbum }