SharePoster.vue
16.9 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
<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>
<!-- 生成中提示 -->
<div v-if="is_generating" class="text-center text-gray-500 text-sm mb-2">正在生成海报...</div>
<!-- 海报区域:直接使用 Canvas 合成的图片,支持长按保存 -->
<!-- 当已生成海报图时,容器不再应用卡片边框与阴影,避免双重边框视觉效果;降级展示仍保留卡片样式 -->
<div :class="poster_img_src ? 'PosterCard mx-auto' : 'PosterCard bg-white rounded-xl overflow-hidden border border-gray-200 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 rounded-t-xl overflow-hidden">
<img :src="cover_final_src" alt="课程封面" class="w-full h-auto object-contain" crossorigin="anonymous" />
</div>
<!-- 下部信息区:左二维码 + 右文案 -->
<div class="PosterInfo p-4 bg-white">
<div class="flex items-start">
<!-- 左侧二维码 -->
<div class="PosterQR mr-4">
<img :src="qr_final_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 } from 'vue'
import { toPng } from 'html-to-image'
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') {
// CDN 图片统一追加压缩参数,若地址未包含 imageMogr2,则追加压缩参数
// const param = 'imageMogr2/thumbnail/200x/strip/quality/70'
// const has_mogr = url.includes('imageMogr2')
// if (!has_mogr) {
// return url + (url.includes('?') ? '&' : '?') + param
// }
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)
/**
* @var {import('vue').Ref<boolean>} is_generating
* @description 是否处于海报生成中状态,用于在弹窗内展示“正在生成海报...”提示。
*/
const is_generating = ref(false)
/** 标题/副标题/介绍 */
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 || ''))
/**
* @var {import('vue').Ref<string>} cover_data_url
* @description 封面图的 base64;优先用 base64 以避免跨域获取失败
*/
const cover_data_url = ref('')
/** 最终封面图地址:优先使用 base64,否则回退原地址 */
const cover_final_src = computed(() => cover_data_url.value || cover_src.value)
/**
* @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)
})
/**
* @var {import('vue').Ref<string>} qr_data_url
* @description 本地生成的二维码 base64,避免跨域图片导致生成失败
*/
const qr_data_url = ref('')
/** 最终二维码地址:优先使用本地生成的 base64,否则回退服务端地址 */
const qr_final_src = computed(() => qr_data_url.value || qr_src.value)
// 海报图片 dataURL(用于长按保存)
const poster_img_src = ref('')
/**
* @function try_fetch_to_data_url
* @description 尝试将图片地址转为 base64;跨域或失败时返回空串。
* @param {string} url 图片地址
* @returns {Promise<string>} base64 dataURL 或空串
*/
async function try_fetch_to_data_url(url) {
if (!url) return ''
try {
const res = await fetch(url, { mode: 'cors', cache: 'no-cache', credentials: 'omit' })
if (!res.ok) return ''
const blob = await res.blob()
return await new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => resolve(String(reader.result || ''))
reader.onerror = () => resolve('')
reader.readAsDataURL(blob)
})
} catch (e) {
return ''
}
}
/**
* @function prepare_assets
* @description 在截图前准备资源:封面尝试转 base64、二维码本地生成为 base64。
* @returns {Promise<void>}
*/
async function prepare_assets() {
// 二维码本地生成
try {
const url = props.qr_url || (typeof window !== 'undefined' ? window.location.href : '')
const data_url = await QRCode.toDataURL(url, { margin: 2, width: 256, color: { dark: '#000000', light: '#ffffff' } })
qr_data_url.value = data_url || ''
} catch (e) {
qr_data_url.value = ''
}
// 封面尝试转 base64(若跨域失败则回退原地址)
try {
const b64 = await try_fetch_to_data_url(cover_src.value)
cover_data_url.value = b64 || ''
} catch (e) {
cover_data_url.value = ''
}
}
/**
* @function compose_poster
* @description 使用 html-to-image 对可视卡片 DOM 截图并生成 PNG 的 dataURL,仅在弹窗打开时触发。
* @returns {Promise<void>}
*/
async function compose_poster() {
poster_img_src.value = ''
try {
// 标记进入生成流程
is_generating.value = true
// 准备资源,尽量使用 base64 避免跨域失败
await prepare_assets()
await nextTick()
const node = card_ref.value
if (!node) {
is_generating.value = false
return
}
// 等待容器内图片加载完成,避免首次截图丢失封面
await wait_images_loaded(node)
// 轻微延迟,确保弹窗过渡动画结束,布局稳定
await new Promise(r => setTimeout(r, 80))
// 克隆离屏节点,避免弹窗动画与布局抖动影响截图
const { wrapper, clone, size } = create_offscreen_clone(node)
await wait_images_loaded(clone, 1200)
// 设置像素比例,提升清晰度(在高分屏上更清晰)
const pixel_ratio = Math.max(1, Math.min(2.5, window.devicePixelRatio || 1))
// 透明 1x1 PNG 作为占位图,避免资源获取失败直接中断
const placeholder = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wm3T9kAAAAASUVORK5CYII='
// 生成 PNG dataURL
// 设置背景为透明,保留圆角的透明角,避免白色四角
const data_url = await toPng(clone, {
pixelRatio: pixel_ratio,
cacheBust: true,
backgroundColor: 'transparent',
imagePlaceholder: placeholder,
fetchRequestInit: { mode: 'cors', cache: 'no-cache', credentials: 'omit' },
// 避免外层 margin 影响截图结果
style: { margin: '0' },
width: Math.round(size.width),
height: Math.round(size.height)
})
poster_img_src.value = data_url
// 清理离屏节点
if (wrapper && wrapper.parentNode) wrapper.parentNode.removeChild(wrapper)
is_generating.value = false
} catch (err) {
console.error('html-to-image 生成海报失败:', err)
showToast('海报生成失败,已展示标准卡片,请长按保存截图')
poster_img_src.value = ''
is_generating.value = false
}
}
/**
* @function create_offscreen_clone
* @description 创建一个离屏的卡片克隆用于稳定截图,避免受弹窗动画与布局影响。
* @param {HTMLElement} node 原始容器节点
* @returns {{wrapper: HTMLElement, clone: HTMLElement, size: {width: number, height: number}}}
*/
function create_offscreen_clone(node) {
const rect = node.getBoundingClientRect()
const size = { width: rect.width, height: rect.height }
const wrapper = document.createElement('div')
const clone = node.cloneNode(true)
// 离屏包裹容器样式
Object.assign(wrapper.style, {
position: 'fixed',
left: '-99999px',
top: '-99999px',
width: `${Math.round(size.width)}px`,
height: `${Math.round(size.height)}px`,
overflow: 'hidden',
opacity: '0',
pointerEvents: 'none',
background: 'transparent',
zIndex: '-1000'
})
// 克隆节点样式校正,避免动画、阴影、滤镜干扰
Object.assign(clone.style, {
width: '100%',
height: '100%',
margin: '0',
transform: 'none',
filter: 'none',
boxShadow: 'none'
})
wrapper.appendChild(clone)
document.body.appendChild(wrapper)
return { wrapper, clone, size }
}
/**
* @function watch_open_and_generate
* @description 仅在弹窗打开时开始生成海报;关闭不生成。每次打开都重新生成以保证信息最新。
* @returns {void}
*/
watch(show_proxy, (opened) => {
if (opened) {
if (is_generating.value) return
poster_img_src.value = ''
nextTick(() => compose_poster())
}
})
/**
* @function recompose_on_data_change
* @description 当弹窗处于打开状态且课程数据或二维码地址发生变化时重新合成海报;弹窗关闭时不生成。
* @returns {void}
*/
// 已移除对象引用监听,改为监听具体字段(见下方)
/**
* @function wait_images_loaded
* @description 等待卡片容器中的图片加载完成(或超时),避免首次截图遗漏封面。
* @param {HTMLElement} node 容器节点
* @param {number} timeout 超时时间毫秒
* @returns {Promise<void>}
*/
async function wait_images_loaded(node, timeout = 2500) {
try {
if (!node) return
const imgs = Array.from(node.querySelectorAll('img'))
if (!imgs.length) return
await Promise.all(imgs.map(img => new Promise((resolve) => {
if (img.complete) return resolve()
let done = false
const finish = () => { if (!done) { done = true; resolve() } }
img.addEventListener('load', finish, { once: true })
img.addEventListener('error', finish, { once: true })
setTimeout(finish, timeout)
})))
} catch (_) {
// 忽略加载异常,继续生成
}
}
// 调整数据变更监听:仅在封面地址或二维码地址变化时重新生成
watch([() => props.course?.cover, () => props.qr_url], () => {
if (show_proxy.value) {
if (is_generating.value) return
poster_img_src.value = ''
nextTick(() => compose_poster())
}
})
</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 {
width: 100%;
// 使用自适应高度,内部图片使用 object-contain 保持完整显示
border-top-left-radius: 16px;
border-top-right-radius: 16px;
overflow: hidden;
}
.PosterInfo {
overflow: hidden;
.PosterQR {
img {
box-shadow: none;
}
}
}
}
}
</style>