SharePoster.vue
20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
<template>
<!-- 弹窗容器:展示分享海报 -->
<van-popup
v-model:show="show_proxy"
round
position="bottom"
:style="{ width: '100%' }"
>
<div class="PosterWrapper p-4">
<!-- 标题与关闭按钮 -->
<div class="flex justify-between items-center mb-3">
<h3 class="font-medium">分享课程</h3>
<van-icon name="cross" @click="close" />
</div>
<!-- 海报区域:直接使用 Canvas 合成的图片,支持长按保存 -->
<!-- 当已生成海报图时,容器不再应用卡片边框与阴影,避免双重边框视觉效果;降级展示仍保留卡片样式 -->
<div :class="poster_img_src ? 'PosterCard mx-auto' : 'PosterCard bg-white rounded-xl shadow-md overflow-hidden mx-auto'" ref="card_ref">
<img v-if="poster_img_src" :src="poster_img_src" alt="分享海报" class="w-full h-auto object-contain block" />
<!-- 生成失败或尚未生成时的降级展示(可长按截图保存) -->
<div v-else>
<!-- 上部封面图 -->
<div class="PosterCover">
<img :src="cover_src" alt="课程封面" class="w-full h-full object-cover" crossorigin="anonymous" />
</div>
<!-- 下部信息区:左二维码 + 右文案 -->
<div class="PosterInfo p-4">
<div class="flex items-start">
<!-- 左侧二维码 -->
<div class="PosterQR mr-4">
<img :src="qr_src" alt="课程二维码" class="w-24 h-24 rounded" crossorigin="anonymous" />
</div>
<!-- 右侧文案 -->
<div class="flex-1 flex flex-col space-y-2 -mt-1">
<div class="text-lg font-semibold text-gray-800 truncate leading-tight -mt-0.5">{{ title_text }}</div>
<div class="text-sm text-gray-500 truncate" v-if="subtitle_text">{{ subtitle_text }}</div>
<div class="text-lg text-gray-400 truncate" v-if="date_range_text">{{ date_range_text }}</div>
</div>
</div>
<div class="mt-4 text-green-600 text-base">扫码了解详情</div>
</div>
</div>
</div>
<!-- 底部提示与关闭按钮 -->
<div class="mt-3 text-center text-gray-500 text-xs">长按图片保存</div>
<div class="mt-4">
<button class="w-full bg-green-500 text-white py-2 rounded-lg" @click="close">关闭</button>
</div>
</div>
</van-popup>
<van-back-top right="5vw" bottom="25vh" offset="600" />
</template>
<script setup>
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import QRCode from 'qrcode'
import { showToast } from 'vant'
/**
* @typedef {Object} CourseLike
* @property {string} [title] 课程标题
* @property {string} [subtitle] 课程副标题
* @property {string} [cover] 课程封面地址
* @property {string} [introduce] 课程介绍(可包含HTML)
* @property {string} [start_at] 开始日期(可选)
* @property {string} [end_at] 结束日期(可选)
*/
/**
* @function normalize_image_url
* @param {string} src 原始图片地址
* @returns {string} 处理后的图片地址
*/
function normalize_image_url(src) {
const url = src || ''
if (!url) return ''
try {
const u = new URL(url, window.location.origin)
if (u.hostname === 'cdn.ipadbiz.cn' && !u.search) {
return `${url}`
}
} catch (e) {
// 非绝对路径或无法解析的场景,直接返回原值
}
return url
}
const props = defineProps({
/** 弹窗显隐(v-model:show) */
show: { type: Boolean, default: false },
/** 课程对象(动态生成海报所需信息) */
course: { type: Object, default: () => ({}) },
/** 二维码跳转地址(默认当前页面URL) */
qr_url: { type: String, default: '' }
})
const emit = defineEmits(['update:show'])
/**
* @function close
* @description 关闭弹窗
* @returns {void}
*/
const close = () => {
emit('update:show', false)
}
/**
* @function show_proxy
* @description 将 `props.show` 映射为可写的计算属性以支持 v-model:show
*/
const show_proxy = computed({
get() { return props.show },
set(v) { emit('update:show', v) }
})
/**
* @var {import('vue').Ref<HTMLElement|null>} card_ref
* @description 海报卡片容器引用,用于动态获取容器宽度以计算 Canvas 尺寸
*/
const card_ref = ref(null)
/** 标题/副标题/介绍 */
const title_text = computed(() => props.course?.title || '课程')
const subtitle_text = computed(() => props.course?.subtitle || '')
/**
* @function strip_html
* @description 将富文本介绍转换为纯文本并截断展示。
* @param {string} html 原始HTML
* @returns {string} 纯文本
*/
function strip_html(html) {
return (html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
}
const intro_text = computed(() => {
const raw = props.course?.introduce || ''
const text = strip_html(raw)
return text
})
/**
* @function format_date
* @description 将时间字符串转为 `YYYY-MM-DD` 格式;无法解析则返回原字符串。
* @param {string} s 时间字符串
* @returns {string} 处理后的日期字符串
*/
function format_date(s) {
if (!s) return ''
const t = String(s).trim()
if (t.length >= 10) return t.slice(0, 10)
const d = new Date(t)
if (!isNaN(d.getTime())) {
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${dd}`
}
return t
}
/** 日期范围(若有) */
const date_range_text = computed(() => {
const s = props.course?.course_start_time || props.course?.start_at || ''
const e = props.course?.course_end_time || props.course?.end_at || ''
if (s && e) return `${format_date(s)} 至 ${format_date(e)}`
return ''
})
/** 封面图地址(含CDN压缩规则) */
const cover_src = computed(() => normalize_image_url(props.course?.cover || ''))
/**
* @function build_qr_service_url
* @description 按项目接口规则拼接二维码服务地址:`origin/admin/?m=srv&a=get_qrcode&key=实际地址`
* @param {string} raw_url 实际跳转地址
* @returns {string} 可直接用于 img 的二维码服务地址
*/
function build_qr_service_url(raw_url) {
const origin = import.meta.env.VITE_PROXY_TARGET || (typeof window !== 'undefined' ? window.location.origin : '')
// 规整 origin,确保以 / 结尾便于 URL 组合
const base = origin.endsWith('/') ? origin : origin + '/'
const api = new URL('admin/?m=srv&a=get_qrcode', base)
const key = encodeURIComponent(raw_url || '')
api.searchParams.set('key', raw_url ? raw_url : '')
// 某些服务不识别 searchParams 的编码方式,这里直接拼接编码后的 key 以确保兼容
return `${api.origin}${api.pathname}?m=srv&a=get_qrcode&key=${key}`
}
/** 二维码图片(通过项目接口获取) */
const qr_src = computed(() => {
const url = props.qr_url || (typeof window !== 'undefined' ? window.location.href : '')
return build_qr_service_url(url)
})
// 海报图片 dataURL(用于长按保存)
const poster_img_src = ref('')
/**
* @function load_image
* @description 以匿名跨域方式加载图片并追加时间戳防缓存;失败返回 null。
* @param {string} src 图片地址
* @returns {Promise<HTMLImageElement|null>} 加载成功的图片对象或 null
*/
function load_image(src) {
return new Promise((resolve) => {
if (!src) return resolve(null)
const img = new Image()
img.crossOrigin = 'anonymous'
const with_ts = src + (src.includes('?') ? '&' : '?') + 'v=' + Date.now()
img.onload = () => resolve(img)
img.onerror = () => resolve(null)
img.src = with_ts
})
}
/**
* @function wrap_text
* @description 按最大宽度自动换行并限制最大行数;溢出末行追加省略号。
* @param {CanvasRenderingContext2D} ctx 画布上下文
* @param {string} text 文本内容
* @param {number} max_w 最大宽度
* @param {string} font 字体样式(如 'bold 32px sans-serif')
* @param {number} line_h 行高
* @param {number} max_lines 最大行数
* @returns {string[]} 处理后的行数组
*/
function wrap_text(ctx, text, max_w, font, line_h, max_lines) {
ctx.font = font
const content = (text || '').trim()
if (!content) return []
const lines = []
let cur = ''
const tokens = Array.from(content)
tokens.forEach(ch => {
const test = cur + ch
if (ctx.measureText(test).width <= max_w) {
cur = test
} else {
lines.push(cur)
cur = ch
}
})
if (cur) lines.push(cur)
if (lines.length > max_lines) {
const truncated = lines.slice(0, max_lines)
const last = truncated[truncated.length - 1]
truncated[truncated.length - 1] = (last || '').slice(0, Math.max(0, (last || '').length - 1)) + '…'
return truncated
}
return lines
}
/**
* @function rounded_rect_path
* @description 绘制圆角矩形路径(仅定义 path,不进行填充或描边)。
* @param {CanvasRenderingContext2D} ctx 画布上下文
* @param {number} x 起始x
* @param {number} y 起始y
* @param {number} w 宽度
* @param {number} h 高度
* @param {number} r 圆角半径
* @returns {void}
*/
function rounded_rect_path(ctx, x, y, w, h, r) {
const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2))
ctx.beginPath()
ctx.moveTo(x + rr, y)
ctx.lineTo(x + w - rr, y)
ctx.quadraticCurveTo(x + w, y, x + w, y + rr)
ctx.lineTo(x + w, y + h - rr)
ctx.quadraticCurveTo(x + w, y + h, x + w - rr, y + h)
ctx.lineTo(x + rr, y + h)
ctx.quadraticCurveTo(x, y + h, x, y + h - rr)
ctx.lineTo(x, y + rr)
ctx.quadraticCurveTo(x, y, x + rr, y)
ctx.closePath()
}
/**
* @function compose_poster
* @description 以 Canvas 合成海报:上部封面、左侧二维码、右侧文本信息;生成 dataURL 供长按保存。
* @returns {Promise<void>}
*/
/**
* @function compose_poster
* @description 以 Canvas 合成海报:底部仅渲染标题与副标题,右侧居中排版;生成 dataURL 供长按保存。
* @returns {Promise<void>}
*/
async function compose_poster() {
poster_img_src.value = ''
try {
// 固定设计宽度与纵横比,避免因容器导致放大模糊
const width = 750
const aspect_ratio = 1 // 高度 = 宽度 * 1
const height = Math.round(width * aspect_ratio)
// 卡片外边距,用于投影显示空间;卡片圆角与投影参数
const card_margin = 12
const card_x = card_margin
const card_y = card_margin
const card_w = width - card_margin * 2
const card_h = height - card_margin * 2
const card_radius = 16
// 调整封面与信息区比例:封面 2/3,高度留出更多信息区避免裁切(基于卡片内容高度)
const cover_h = Math.round(card_h * 2 / 3)
const info_h = card_h - cover_h
const padding = 32
const info_body_h = info_h - padding * 2
// 二维码尺寸不超过信息区有效高度,保留少量安全边距,防止底部被裁切
const qr_size = Math.floor(Math.min(196, Math.max(96, info_body_h - 4)))
const title_font = 'bold 36px -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei"'
const subtitle_font = 'normal 24px -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei"'
const date_font = 'normal 28px -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei"'
const footnote_font = 'normal 24px -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei"'
const measurer = document.createElement('canvas')
const mctx = measurer.getContext('2d')
const text_max_w = card_w - padding * 2 - qr_size - 20
// 测量标题/副标题/日期,并在信息区顶部对齐排版(脚注单独贴底绘制)
const title_lines = wrap_text(mctx, title_text.value, text_max_w, title_font, 44, 1)
const subtitle_lines = subtitle_text.value ? wrap_text(mctx, subtitle_text.value, text_max_w, subtitle_font, 32, 1) : []
const date_lines = date_range_text.value ? wrap_text(mctx, date_range_text.value, text_max_w, date_font, 40, 1) : []
// 文本行间距:用于增大标题/副标题/日期的间隔
const line_gap = 10
const lines_count = (title_lines.length ? 1 : 0) + (subtitle_lines.length ? 1 : 0) + (date_lines.length ? 1 : 0)
const gaps_count = Math.max(0, lines_count - 1)
const total_text_h = (title_lines.length ? 44 : 0)
+ (subtitle_lines.length ? 32 : 0)
+ (date_lines.length ? 40 : 0)
+ gaps_count * line_gap
const text_offset_y = 0
const dpr = Math.max(1, Math.min(2, window.devicePixelRatio || 1))
const canvas = document.createElement('canvas')
canvas.width = Math.round(width * dpr)
canvas.height = Math.round(height * dpr)
const ctx = canvas.getContext('2d')
ctx.scale(dpr, dpr)
// 卡片阴影与背景(白色圆角卡片 + 灰色边框)
ctx.save()
rounded_rect_path(ctx, card_x, card_y, card_w, card_h, card_radius)
ctx.shadowColor = 'rgba(0,0,0,0.12)'
ctx.shadowBlur = 12
ctx.shadowOffsetX = 0
ctx.shadowOffsetY = 4
ctx.fillStyle = '#ffffff'
ctx.fill()
ctx.restore()
// 卡片边框
ctx.save()
rounded_rect_path(ctx, card_x, card_y, card_w, card_h, card_radius)
ctx.strokeStyle = '#e5e7eb' // gray-200
ctx.lineWidth = 2
ctx.stroke()
ctx.restore()
// 卡片内容裁剪区域
ctx.save()
rounded_rect_path(ctx, card_x, card_y, card_w, card_h, card_radius)
ctx.clip()
// 封面图(严格裁剪到封面区域,避免溢出到信息区)
const cover_img = await load_image(cover_src.value)
if (cover_img) {
const sw = cover_img.width
const sh = cover_img.height
const dest_ar = card_w / cover_h
const src_ar = sw / sh
let sx = 0, sy = 0, s_w = sw, s_h = sh
// 根据源图与目标区域的纵横比,选择水平或垂直裁剪
if (src_ar > dest_ar) {
// 源图更宽:水平裁剪
s_h = sh
s_w = Math.round(sh * dest_ar)
sx = Math.round((sw - s_w) / 2)
sy = 0
} else {
// 源图更窄或更高:垂直裁剪
s_w = sw
s_h = Math.round(sw / dest_ar)
sx = 0
sy = Math.round((sh - s_h) / 2)
}
// 目标区域严格限定在封面矩形
ctx.save()
ctx.beginPath()
ctx.rect(card_x, card_y, card_w, cover_h)
ctx.clip()
ctx.drawImage(cover_img, sx, sy, s_w, s_h, card_x, card_y, card_w, cover_h)
ctx.restore()
} else {
ctx.fillStyle = '#f3f4f6' // gray-100
ctx.fillRect(card_x, card_y, card_w, cover_h)
ctx.fillStyle = '#9ca3af' // gray-400
ctx.textAlign = 'center'
ctx.font = 'normal 20px -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei"'
ctx.fillText('封面加载失败', card_x + card_w / 2, card_y + cover_h / 2 + 10)
ctx.textAlign = 'left'
}
// 二维码(本地生成避免跨域)
const qr_canvas = document.createElement('canvas')
qr_canvas.width = Math.round(qr_size * dpr)
qr_canvas.height = Math.round(qr_size * dpr)
const qr_url_val = props.qr_url || (typeof window !== 'undefined' ? window.location.href : '')
try {
await QRCode.toCanvas(qr_canvas, qr_url_val, { width: Math.round(qr_size * dpr), margin: Math.round(2 * dpr), color: { dark: '#000000', light: '#ffffff' } })
} catch (e) {
const qctx = qr_canvas.getContext('2d')
qctx.fillStyle = '#ffffff'
qctx.fillRect(0, 0, Math.round(qr_size * dpr), Math.round(qr_size * dpr))
qctx.strokeStyle = '#e5e7eb'
qctx.strokeRect(0, 0, Math.round(qr_size * dpr), Math.round(qr_size * dpr))
qctx.fillStyle = '#9ca3af'
qctx.font = `${Math.round(16 * dpr)}px -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei"`
qctx.fillText('二维码生成失败', Math.round(12 * dpr), Math.round((qr_size * dpr) / 2))
}
ctx.drawImage(qr_canvas, card_x + padding, card_y + cover_h + padding, qr_size, qr_size)
// 文案(右侧,顶部对齐)
let tx = card_x + padding + qr_size + 20
let ty = card_y + cover_h + padding
ctx.fillStyle = '#1f2937' // gray-800
ctx.font = title_font
// 增加标题与后续文本的间距
title_lines.forEach(line => { ctx.fillText(line, tx, ty + 34); ty += 44 + line_gap })
ctx.fillStyle = '#6b7280' // gray-500
ctx.font = subtitle_font
// 增加副标题与后续文本的间距
subtitle_lines.forEach(line => { ctx.fillText(line, tx, ty + 24); ty += 32 + line_gap })
ctx.fillStyle = '#9ca3af' // gray-400
ctx.font = date_font
// 日期作为最后一行,不再额外叠加间距
date_lines.forEach(line => { ctx.fillText(line, tx, ty + 30); ty += 40 })
// 脚注:底部绿色提示文案(贴底显示)
ctx.fillStyle = '#10b981' // green-500
ctx.font = footnote_font
let foot_y = card_y + cover_h + info_h - padding - 14
// 保证脚注与上方文本至少保留最小间距
const min_gap = 24
const last_text_bottom_y = ty
if (foot_y - last_text_bottom_y < min_gap) {
foot_y = last_text_bottom_y + min_gap
}
ctx.fillText('扫码了解详情', tx, foot_y)
// 恢复裁剪
ctx.restore()
// 生成 dataURL
try {
const data_url = canvas.toDataURL('image/png')
poster_img_src.value = data_url
} catch (e) {
console.error('海报生成失败(跨域):', e)
showToast('海报生成失败,已展示标准卡片,请长按保存截图')
poster_img_src.value = ''
}
} catch (err) {
console.error('compose_poster 异常:', err)
showToast('海报生成失败,请稍后重试')
poster_img_src.value = ''
}
}
/**
* @function init_once
* @description 组件挂载时生成一次海报,避免因弹框开关导致重复计算与变形。
* @returns {void}
*/
onMounted(() => {
if (!poster_img_src.value) {
nextTick(() => compose_poster())
}
})
/**
* @function recompose_on_data_change
* @description 仅当课程数据或二维码地址发生变化时重新合成海报;避免因弹窗显隐导致的重复计算。
* @returns {void}
*/
watch(() => [props.course, props.qr_url], () => {
nextTick(() => compose_poster())
}, { deep: false })
</script>
<style lang="less" scoped>
.PosterWrapper {
height: auto;
display: flex;
flex-direction: column;
.PosterCard {
width: 100%;
max-width: 750px;
height: auto;
margin: 0 auto;
display: block;
> img {
width: 100%;
height: auto;
object-fit: contain;
display: block;
}
.PosterCover {
// 固定封面高度为卡片宽度的 2/3,避免溢出到信息区
aspect-ratio: 3 / 2;
width: 100%;
overflow: hidden;
}
.PosterInfo {
overflow: hidden;
.PosterQR {
img {
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}
}
}
}
}
</style>