feat(share): 个人推广更换背景图

This commit is contained in:
woody 2025-06-13 17:16:37 +08:00
parent 20b8a20ae0
commit 29cd1c40e1
4 changed files with 436 additions and 260 deletions

View File

@ -20,7 +20,7 @@ module.exports = vm => {
//#ifdef DEV_SERVER
console.log('DEV_SERVER')
config.baseURL = 'http://t-app.beida777.com/prod-api'
config.baseURL = 'http://localhost:8080'
//#endif
//#ifdef QA_SERVER

2
package-lock.json generated
View File

@ -3532,7 +3532,7 @@
},
"node_modules/html2canvas": {
"version": "1.4.1",
"resolved": "https://registry.npmmirror.com/html2canvas/-/html2canvas-1.4.1.tgz",
"resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz",
"integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==",
"license": "MIT",
"dependencies": {

View File

@ -1,7 +1,9 @@
<template>
<view class="share-container">
<!-- This is the content that will be shared as an image -->
<view class="share-content" :class="{ 'is-loaded': isLoaded }">
<view id="shareContainer" class="share-container">
<!-- Portal Frame: The main content to be saved. -->
<view class="portal-frame" :class="{ 'is-loaded': isLoaded }">
<!-- The single, robust QR Code card -->
<view class="qr-code-outer">
<image
class="qr-code"
:src="qrCodeImage"
@ -13,13 +15,11 @@
</view>
</view>
<button
class="share-button"
:class="{ 'is-loaded': isLoaded }"
@click="sharePage"
>
<!-- The real, clickable button -->
<button class="share-button" @click="sharePage" v-show="shareButtonShow">
保存图片并分享
</button>
</view>
<!-- Canvas for generating the share image, positioned off-screen -->
<canvas
@ -35,6 +35,7 @@
</template>
<script>
import html2canvas from 'html2canvas'
import { getShareCode } from '@/config/share'
export default {
@ -44,8 +45,9 @@ export default {
qrCodeImage: '',
// Set canvas dimensions. It's better to get device screen width for this.
canvasWidth: 375,
canvasHeight: 550,
canvasHeight: 800,
isLoaded: false,
shareButtonShow: true,
}
},
onLoad() {
@ -54,8 +56,8 @@ export default {
uni.getSystemInfo({
success: res => {
this.canvasWidth = res.windowWidth
// Adjust height proportionally or keep it fixed
this.canvasHeight = res.windowWidth * 1.4
// Set canvas height to a fixed 800px as requested
this.canvasHeight = 800
},
})
},
@ -98,68 +100,273 @@ export default {
})
return
}
this.shareButtonShow = false
uni.showLoading({ title: '正在生成图片...' })
try {
const tempImagePath = await this.base64ToTempFilePath(this.qrCodeImage)
if (!tempImagePath) {
throw new Error('图片处理失败')
// --- Button Swap Logic ---
this.shareButtonShow = false
// Wait for DOM to update with the fake button
await this.$nextTick()
// #ifdef H5
// Capture the entire container as requested
await this.captureWithHtml2Canvas()
// #endif
// #ifndef H5
// Draw the entire container using Canvas
await this.generateImageWithCanvas()
// #endif
} catch (error) {
uni.hideLoading()
uni.showToast({ title: '图片生成失败,请稍后重试', icon: 'none' })
console.error('sharePage error:', error)
} finally {
// --- Always swap back to the real button ---
this.shareButtonShow = true
}
},
// --- H5-specific method ---
captureWithHtml2Canvas() {
return new Promise((resolve, reject) => {
// #ifdef H5
// Target the entire #shareContainer as per instruction
const element = document.getElementById('shareContainer')
if (!element) {
uni.hideLoading()
return reject(new Error('Share container element not found'))
}
html2canvas(element, {
useCORS: true,
allowTaint: true,
backgroundColor: null,
scale: window.devicePixelRatio || 2,
logging: false,
})
.then(canvas => {
this.saveImageToAlbum(canvas.toDataURL('image/png', 1.0))
resolve()
})
.catch(err => {
console.error('html2canvas capture failed:', err)
reject(err)
})
// #endif
})
},
// A robust canvas-based image generation for all platforms
async generateImageWithCanvas() {
try {
// Load all required images before drawing
const [bgImageTempPath, qrCodeTempPath] = await Promise.all([
this.getLocalImageTempPath('/static/images/share-bg.png'),
this.base64ToTempFilePath(this.qrCodeImage),
])
if (!bgImageTempPath || !qrCodeTempPath) {
throw new Error('Image resource failed to load')
}
const ctx = uni.createCanvasContext('shareCanvas', this)
this.drawShareImage(ctx, tempImagePath)
// Draw the entire scene to the canvas
this.drawSceneToCanvas(ctx, bgImageTempPath, qrCodeTempPath)
return new Promise(resolve => {
setTimeout(() => {
ctx.draw(false, () => {
setTimeout(() => {
this.saveCanvasToAlbum()
resolve()
}, 500)
})
}, 100)
})
} catch (error) {
uni.hideLoading()
uni.showToast({ title: error.message || '图片生成失败', icon: 'none' })
console.error('sharePage error:', error)
console.error('generateImageWithCanvas error:', error)
throw error
}
},
drawShareImage(ctx, tempImagePath) {
// Main drawing function to replicate the entire scene on canvas
drawSceneToCanvas(ctx, bgPath, qrPath) {
const canvasWidth = this.canvasWidth
const canvasHeight = this.canvasHeight
const canvasHeight = this.canvasHeight // Fixed at 800px
// White background
ctx.fillStyle = '#FFFFFF'
ctx.fillRect(0, 0, canvasWidth, canvasHeight)
// 1. Draw background image
ctx.drawImage(bgPath, 0, 0, canvasWidth, canvasHeight)
// Title
ctx.setFontSize(22)
ctx.fillStyle = '#1e1e1e'
ctx.textAlign = 'center'
ctx.fillText('扫码注册', canvasWidth / 2, 70)
// 2. Draw portal frame (calculations for centering)
const portalWidth = canvasWidth * 0.85
const portalPadding = 20
// The white card's width is the portal's inner width
const cardWidth = portalWidth - portalPadding * 2
// The card is a square, so its height is its width
const cardHeight = cardWidth
const buttonHeight = 50
const buttonMargin = 20
const portalHeight =
portalPadding * 2 + cardHeight + buttonMargin + buttonHeight
const portalX = (canvasWidth - portalWidth) / 2
const portalY = (canvasHeight - portalHeight) / 2
this.drawPortalFrame(ctx, portalX, portalY, portalWidth, portalHeight)
// QR Code Image
const qrCodeSize = canvasWidth * 0.7
const qrCodeX = (canvasWidth - qrCodeSize) / 2
const qrCodeY = 120
ctx.drawImage(tempImagePath, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize)
// 3. Draw the white QR card
const cardX = portalX + portalPadding
const cardY = portalY + portalPadding
this.drawQrCodeCard(ctx, cardX, cardY, cardWidth, cardHeight)
// Tip text
ctx.setFontSize(15)
ctx.fillStyle = '#888'
ctx.textAlign = 'center'
ctx.fillText(
'扫描二维码,即可完成操作',
canvasWidth / 2,
qrCodeY + qrCodeSize + 50
// 4. Draw the FAKE button to match the CSS
const buttonX = cardX
const buttonY = cardY + cardHeight + buttonMargin
this.drawStyledButton(
ctx,
buttonX,
buttonY,
cardWidth,
buttonHeight,
'保存图片并分享'
)
// 5. Draw the actual QR image (or loader placeholder) on top
// If qrPath is null/empty, this block is skipped, leaving the white card empty (like a placeholder)
if (qrPath) {
// Padding inside the white card
const imagePadding = cardWidth * 0.1
const qrCodeSize = cardWidth - imagePadding * 2
const qrCodeX = cardX + imagePadding
const qrCodeY = cardY + imagePadding
ctx.drawImage(qrPath, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize)
} else {
// Draw loader manually if QR is not available
// This part is complex, for now we show an empty card which is better than broken UI
}
},
// Helper: Draws the portal frame to match CSS
drawPortalFrame(ctx, x, y, width, height) {
const radius = 25 // 50rpx
ctx.save()
this.drawRoundedRect(ctx, x, y, width, height, radius)
// Frosted glass effect
const portalGradient = ctx.createLinearGradient(x, y, x, y + height)
portalGradient.addColorStop(0, 'rgba(255, 255, 255, 0.4)')
portalGradient.addColorStop(1, 'rgba(255, 255, 255, 0.2)')
ctx.fillStyle = portalGradient
ctx.fill()
// Inner glow border
ctx.shadowColor = 'rgba(255, 255, 255, 0.5)'
ctx.shadowBlur = 10
ctx.strokeStyle = 'rgba(255, 255, 255, 0.6)'
ctx.lineWidth = 1.5
ctx.stroke()
ctx.restore()
},
// New/Refactored Helper: Draws the single white QR Code card
drawQrCodeCard(ctx, x, y, width, height) {
const borderRadius = 20 // 40rpx
ctx.save()
this.drawRoundedRect(ctx, x, y, width, height, borderRadius)
// Card background
ctx.fillStyle = 'rgba(255, 255, 255, 0.98)'
// Card shadow
ctx.shadowColor = 'rgba(50, 50, 90, 0.1)'
ctx.shadowBlur = 30
ctx.shadowOffsetY = 15
ctx.fill()
// Card border
ctx.strokeStyle = '#f0f0f0'
ctx.lineWidth = 1
ctx.stroke()
ctx.restore()
},
// Helper: Draws the styled button
drawStyledButton(ctx, x, y, width, height, text) {
const radius = height / 2
ctx.save()
this.drawRoundedRect(ctx, x, y, width, height, radius)
// Background gradient
const gradient = ctx.createLinearGradient(x, y, x + width, y)
gradient.addColorStop(0, '#0ff0fc')
gradient.addColorStop(0.5, '#0072ff')
gradient.addColorStop(1, '#00c6ff')
ctx.fillStyle = gradient
// Shadow
ctx.shadowColor = 'rgba(0, 114, 255, 0.35)'
ctx.shadowBlur = 20
ctx.shadowOffsetY = 8
ctx.fill()
ctx.restore()
// Text
ctx.save()
ctx.fillStyle = '#ffffff'
ctx.font = '17px sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(text, x + width / 2, y + height / 2)
ctx.restore()
},
// Helper: Draw a rectangle with rounded corners
drawRoundedRect(ctx, x, y, width, height, radius) {
if (width < 2 * radius) radius = width / 2
if (height < 2 * radius) radius = height / 2
ctx.beginPath()
ctx.moveTo(x + radius, y)
ctx.arcTo(x + width, y, x + width, y + height, radius)
ctx.arcTo(x + width, y + height, x, y + height, radius)
ctx.arcTo(x, y + height, x, y, radius)
ctx.arcTo(x, y, x + width, y, radius)
ctx.closePath()
},
saveCanvasToAlbum() {
uni.canvasToTempFilePath(
{
try {
// canvas
const options = {
canvasId: 'shareCanvas',
fileType: 'png',
quality: 1,
success: res => {
console.log('canvas转换成功:', res)
if (res.tempFilePath) {
this.saveImageToAlbum(res.tempFilePath)
} else {
uni.hideLoading()
uni.showToast({ title: '图片生成失败', icon: 'none' })
}
},
fail: err => {
console.error('canvas转换失败:', err)
uni.hideLoading()
uni.showToast({ title: '图片转换失败', icon: 'none' })
},
}
// canvasAPI
uni.canvasToTempFilePath(options, this)
} catch (error) {
console.error('saveCanvasToAlbum error:', error)
uni.hideLoading()
uni.showToast({ title: '保存失败', icon: 'none' })
}
},
//
saveImageToAlbum(filePath) {
// #ifdef H5
// For H5, trigger download instead of saving to album
const link = document.createElement('a')
link.href = res.tempFilePath
link.download = `share_qrcode_${Date.now()}.png`
link.href = filePath
link.download = `share_page_${Date.now()}.png`
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
@ -173,7 +380,7 @@ export default {
// #ifndef H5
// For App and Mini Programs
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
filePath: filePath,
success: () => {
uni.hideLoading()
uni.showToast({
@ -195,9 +402,7 @@ export default {
success: () => {
uni.openSetting({
success(settingdata) {
if (
settingdata.authSetting['scope.writePhotosAlbum']
) {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
uni.showToast({
title: '授权成功,请重试',
icon: 'none',
@ -220,18 +425,10 @@ export default {
})
// #endif
},
fail: err => {
uni.hideLoading()
uni.showToast({ title: '图片转换失败', icon: 'none' })
console.error('canvasToTempFilePath fail:', err)
},
},
this
)
},
base64ToTempFilePath(base64) {
return new Promise((resolve, reject) => {
try {
// #ifdef H5
// For H5, we load the base64 into an Image to ensure it's valid,
// but resolve with the base64 string to avoid Uniapp's internal errors
@ -252,10 +449,22 @@ export default {
// #ifndef H5
// For App and Mini Programs, write to a temp file and return the path.
if (!base64 || typeof base64 !== 'string') {
reject(new Error('无效的base64数据'))
return
}
const formattedBase64 = base64.replace(/^data:image\/\w+;base64,/, '')
if (!formattedBase64) {
reject(new Error('base64数据格式错误'))
return
}
// Use a standard path for user data directory.
const filePath = `${uni.env.USER_DATA_PATH}/share_${Date.now()}.png`
uni.getFileSystemManager().writeFile({
const fileManager = uni.getFileSystemManager()
fileManager.writeFile({
filePath,
data: formattedBase64,
encoding: 'base64',
@ -268,6 +477,10 @@ export default {
},
})
// #endif
} catch (error) {
console.error('base64ToTempFilePath error:', error)
reject(new Error('图片处理失败'))
}
})
},
},
@ -276,13 +489,15 @@ export default {
<style lang="scss" scoped>
.share-container {
justify-content: center;
background: url('@/static/images/share-bg.jpg') no-repeat center center;
background: url('@/static/images/share-bg.png') no-repeat center center;
background-size: 100% 100%;
height: calc(100vh - 80rpx);
box-sizing: border-box;
position: relative;
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
}
.share-bg {
width: 100%;
@ -293,22 +508,28 @@ export default {
}
}
.share-content {
border-radius: 30rpx;
.portal-frame {
/* Restyled to match the ideal screenshot */
background: rgba(255, 255, 255, 0.25);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
padding: 40rpx;
margin-top: 450rpx;
border-radius: 50rpx;
border: 1.5px solid rgba(255, 255, 255, 0.6);
box-shadow:
0 0 0 1.5px rgba(255, 255, 255, 0.4) inset,
0 15rpx 40rpx rgba(0, 0, 0, 0.1);
display: flex;
width: 90%;
box-sizing: border-box;
flex-direction: column;
align-items: center;
width: 100%;
//
margin-top: 480rpx;
position: relative;
z-index: 2;
opacity: 0;
overflow: hidden;
/* Removed margin-top, parent container handles centering */
}
.share-content.is-loaded {
.portal-frame.is-loaded {
opacity: 1;
transform: translateY(0);
}
@ -320,22 +541,37 @@ export default {
margin-bottom: 60rpx;
}
/* The single white card for the QR code */
.qr-code-outer {
width: 100%;
/* This creates a responsive square that's always perfect */
aspect-ratio: 1 / 1;
background: rgba(255, 255, 255, 0.98);
border-radius: 40rpx;
box-shadow: 0px 15rpx 30rpx rgba(50, 50, 90, 0.1);
border: 1px solid #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
padding: 30rpx; /* Padding inside the white card */
box-sizing: border-box;
}
/* The image and the placeholder both live inside the outer card */
.qr-code,
.qr-code-placeholder {
width: 100%;
height: 100%;
}
.qr-code {
width: 450rpx;
height: 450rpx;
margin-bottom: 30rpx;
border-radius: 16rpx;
}
.qr-code-placeholder {
width: 450rpx;
height: 450rpx;
background-color: #f0f2f5;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 30rpx;
border-radius: 16rpx;
}
.loader {
@ -358,93 +594,33 @@ export default {
color: #888;
}
/* Unified style for both the real button and the fake one (which is a view) */
.share-button {
//
margin-top: 20rpx;
width: 450rpx;
background:
linear-gradient(100deg, #0ff0fc 0%, #0072ff 50%, #00c6ff 100%),
linear-gradient(
180deg,
rgba(255, 255, 255, 0.35) 0%,
rgba(0, 0, 0, 0.05) 100%
);
background-blend-mode: lighten, normal;
margin-top: 40rpx;
width: 100%; /* Button takes full width of portal frame padding */
height: 100rpx;
line-height: 100rpx;
color: #fff;
border-radius: 50rpx;
font-size: 34rpx;
height: 100rpx;
line-height: 100rpx;
box-shadow:
0 8rpx 32rpx 0 rgba(0, 255, 255, 0.35),
0 2rpx 8rpx 0 #00eaff99,
0 1.5rpx 0.5rpx 0 #00eaff inset,
0 0 0 4rpx #fff3 inset;
border: 2.5rpx solid #00eaff;
outline: 2rpx solid #fff8;
outline-offset: -4rpx;
position: relative;
overflow: hidden;
z-index: 2;
opacity: 0;
transform: translateY(40rpx);
transition:
transform 0.6s cubic-bezier(0.25, 1, 0.5, 1) 0.1s,
opacity 0.6s ease 0.1s;
/* 立体感 */
text-shadow:
0 2rpx 8rpx #00eaff,
0 1rpx 0 #fff;
/* Match the gradient from canvas drawing */
background: linear-gradient(100deg, #0ff0fc 0%, #0072ff 50%, #00c6ff 100%);
box-shadow: 0 8rpx 20rpx 0 rgba(0, 114, 255, 0.35);
border: none;
padding: 0;
text-align: center;
/* Add transition for the button itself if needed */
}
.share-button::before {
content: '';
position: absolute;
left: -75%;
top: 0;
width: 50%;
height: 100%;
background: linear-gradient(
120deg,
rgba(255, 255, 255, 0.2) 0%,
rgba(0, 255, 255, 0.5) 50%,
rgba(255, 255, 255, 0.2) 100%
);
filter: blur(2px);
transform: skewX(-20deg);
animation: flowing-light 2.2s linear infinite;
pointer-events: none;
}
@keyframes flowing-light {
0% {
left: -75%;
}
100% {
left: 125%;
}
}
.share-button::after {
content: '';
position: absolute;
inset: 0;
border-radius: 50rpx;
box-shadow:
0 0 24rpx 4rpx #00eaff66,
0 0 60rpx 0 #00c6ff33,
0 0 0 4rpx #fff6 inset;
pointer-events: none;
z-index: 1;
}
.share-button.is-loaded {
opacity: 1;
transform: translateY(0);
/* The real button needs to override some uni-app defaults */
button.share-button {
padding: 0;
line-height: 100rpx; /* Ensure text is centered vertically */
border: none;
}
.share-button:active {
transform: translateY(2rpx);
box-shadow: 0 6rpx 12rpx rgba(0, 255, 255, 0.3);
box-shadow: 0 6rpx 12rpx rgba(0, 114, 255, 0.3);
}
</style>

BIN
static/images/share-bg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB