在 canvas 元素中设置宽高为 100%,并使用 canvas 标签的 onReady 回调函数监听 canvas 元素的渲染完成事件。在回调函数中,通过 uni.createSelectorQuery 获取 canvas 元素的高度并更新 canvasHeight 数据。同时,在 touchMove 事件中绘制遮罩层时,使用 canvasHeight 而不是固定值作为高度,实现遮罩层高度自适应。
代码如下:
<template>
<view class="container">
<!-- 上传图片的按钮 -->
<button class="upload-btn" @tap="chooseImage">上传图片</button>
<!-- 展示上传的图片和绘制的遮罩层 -->
<view class="image-wrapper">
<canvas class="mask" :style="{ width: '100%', height: canvasHeight + 'px' }" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" :canvas-id="canvasId"></canvas>
<image :src="imageData" mode="aspectFit" :style="{ width: '100%', height: 'auto' }" />
</view>
<!-- 生成base64格式图片 -->
<button class="generate-btn" @tap="generateImage">生成图片</button>
<!-- 上传图片到服务器 -->
<button class="upload-btn" :disabled="!maskData" @tap="uploadMask">上传</button>
</view>
</template>
<script>
export default {
data() {
return {
canvasId: 'canvas',
canvasHeight: 0,
imageData: '',
maskData: '',
startX: 0,
startY: 0
}
},
methods: {
// 选择图片
chooseImage() {
uni.chooseImage({
count: 1,
success: res => {
this.imageData = res.tempFilePaths[0]
}
})
},
// 绘制遮罩层开始
touchStart(e) {
const { clientX, clientY } = e.changedTouches[0]
this.startX = clientX
this.startY = clientY
},
// 绘制遮罩层移动
touchMove(e) {
const { clientX, clientY } = e.changedTouches[0]
const ctx = uni.createCanvasContext(this.canvasId)
ctx.beginPath()
ctx.moveTo(this.startX, this.startY)
ctx.lineTo(clientX, clientY)
ctx.stroke()
ctx.draw(true)
this.startX = clientX
this.startY = clientY
},
// 绘制遮罩层结束
touchEnd() {
uni.canvasToTempFilePath({
canvasId: this.canvasId,
destWidth: uni.upx2px(750),
destHeight: this.canvasHeight,
success: res => {
this.maskData = res.tempFilePath
}
})
},
// 生成base64格式图片
generateImage() {
uni.canvasToTempFilePath({
canvasId: this.canvasId,
destWidth: uni.upx2px(750),
destHeight: this.canvasHeight,
success: res => {
uni.getImageInfo({
src: res.tempFilePath,
success: info => {
uni.getFileSystemManager().readFile({
filePath: res.tempFilePath,
encoding: 'base64',
success: data => {
this.maskData = 'data:image/' + info.type + ';base64,' + data.data
}
})
}
})
}
})
},
// 上传图片到服务器
uploadMask() {
// 将maskData上传到服务器
},
// canvas渲染完成后获取canvas高度
canvasReady() {
uni.createSelectorQuery().select(`#${this.canvasId}`).boundingClientRect(rect => {
this.canvasHeight = rect.height
}).exec()
}
}
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.upload-btn {
margin-bottom: 20rpx;
}
.image-wrapper {
position: relative;
width: 100%;
}
.generate-btn {
margin-bottom: 20rpx;
}
.upload-btn:disabled {
opacity: 0.4;
pointer-events: none;
}
.mask {
position: absolute;
left: 0;
top: 0;
z-index: 10;
opacity: 0.5;
}
</style>