poster.js 9.1 KB

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