uniapp两张图合并
时间: 2025-02-02 13:09:21 浏览: 37
### 实现 UniApp 中两张图片的合并
在 UniApp 中将两张图片合成为一张主要依赖于 `<canvas>` 组件来完成图像绘制工作。通过 JavaScript 的 Canvas API 可以方便地操作这些图形对象。
#### 创建画布组件
首先,在页面中定义一个 `canvas` 元素用于绘制最终合成后的图片:
```html
<template>
<view class="container">
<!-- 定义 canvas -->
<canvas type="2d" id="myCanvas"></canvas>
<!-- 显示合成后的图片 -->
<image :src="resultImageSrc" mode="widthFix"></image>
<!-- 合成按钮 -->
<button @click="mergeImages">点击合成</button>
</view>
</template>
```
#### 编写脚本逻辑
接着编写 Vue 方法来进行两幅图象的数据获取以及它们之间的组合过程:
```javascript
<script>
export default {
data() {
return {
resultImageSrc: '', // 存储合成之后的结果链接
imagePaths: [
'https://example.com/path/to/image1.png', // 图片一 URL 或本地路径
'https://example.com/path/to/image2.png' // 图片二 URL 或本地路径
]
}
},
methods: {
async mergeImages() {
const ctx = uni.createCanvasContext('myCanvas')
let totalWidth = 0;
let maxHeight = 0;
await Promise.all(this.imagePaths.map(async (path, index) => {
try {
const res = await new Promise((resolve, reject) => {
uni.getImageInfo({
src: path,
success: resolve,
fail: reject
})
});
if(index === 0){
totalWidth += res.width;
maxHeight = Math.max(maxHeight, res.height);
}else{
totalWidth += res.width * maxHeight / res.height;
}
// 设置初始位置以便水平排列
const posX = index === 0 ? 0 : totalWidth - res.width * maxHeight / res.height;
// 将每张图片按比例缩放后绘制到画布上
ctx.drawImage(path, posX, 0, res.width * maxHeight / res.height, maxHeight);
} catch(error){
console.error(`Failed to load or draw image at ${path}`, error);
}
}));
// 更新画布大小适应新尺寸
ctx.canvas.width = totalWidth;
ctx.canvas.height = maxHeight;
// 执行绘图命令
ctx.draw(false, () => {
setTimeout(() => {
// 获取合成后的临时文件路径
uni.canvasToTempFilePath({
x: 0,
y: 0,
width: totalWidth,
height: maxHeight,
destWidth: totalWidth,
destHeight: maxHeight,
canvasId: 'myCanvas',
success: function(res) {
this.resultImageSrc = res.tempFilePath;
}.bind(this),
fail(err) {
console.log("Error converting canvas to temp file:", err);
}
});
}, 50); // 延迟执行确保所有绘图已完成
});
}
}
}
</script>
```
此代码片段展示了如何加载多张远程或本地存储的图片资源,并将其按照指定的方式拼接在一起形成新的单个图像。这里采用了横向连接的方法,即第二张图片会紧挨着第一张放置在其右侧[^1]。
为了使生成的图片能够被用户查看和分享,最后一步是调用 `uni.canvasToTempFilePath()` 函数将 Canvas 上的内容转换为临时文件形式,从而可以直接作为 Image 标签的 source 属性值展示出来[^4]。
阅读全文
相关推荐

















