在 Vue 3 中,结合 html2canvas
来将多张图片合并成一张 6 寸的照片并支持以竖版和横版两种方式打印。Vue 3 主要的变化是在组件生命周期和 ref
的处理方式上。
目录
1. 准备工作
- 安装
html2canvas
用于捕获 DOM 并生成合并的图片。 - 使用 Vue 3 的
ref
和nextTick
管理 DOM 操作。
2. 安装依赖
首先确保安装了 html2canvas
:
npm install html2canvas --save
3. Vue 3 代码实现
<template>
<div>
<!-- 图片容器 -->
<div ref="photoContainer" :style="containerStyle">
<img v-for="(img, index) in images" :key="index" :src="img" :style="imgStyle" />
</div>
<!-- 控制按钮 -->
<div>
<button @click="printPhoto('portrait')">打印竖版照片</button>
<button @click="printPhoto('landscape')">打印横版照片</button>
</div>
</div>
</template>
<script>
import { ref, reactive, nextTick, computed } from 'vue';
import html2canvas from 'html2canvas';
export default {
setup() {
const images = reactive([
// 多张图片的 URL
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
// 你可以添加更多图片
]);
const isPortrait = ref(true); // 是否为竖版
const photoContainer = ref(null); // 引用 DOM 元素
// 计算容器的样式
const containerStyle = computed(() => {
return isPortrait.value
? {
width: '10.16cm', // 竖版宽度
height: '15.24cm', // 竖版高度
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
}
: {
width: '15.24cm', // 横版宽度
height: '10.16cm', // 横版高度
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
};
});
// 图片样式
const imgStyle = {
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
};
// 打印照片的方法
const printPhoto = async (orientation) => {
isPortrait.value = orientation === 'portrait'; // 设置方向
// 等待 DOM 渲染完成
await nextTick();
// 使用 html2canvas 将图片容器渲染为 canvas
const canvas = await html2canvas(photoContainer.value);
const dataUrl = canvas.toDataURL('image/png');
// 创建一个新窗口用于打印
const printWindow = window.open('', '_blank');
printWindow.document.write('<img src="' + dataUrl + '" style="width:100%;height:auto;"/>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
};
return {
images,
photoContainer,
containerStyle,
imgStyle,
printPhoto,
};
},
};
</script>
<style scoped>
/* 你可以根据需要调整样式 */
</style>
4. 解释
images
: 存储多张图片的 URL,通过reactive
来动态管理图片数据。isPortrait
: 一个ref
用于保存当前的打印方向,true
为竖版,false
为横版。photoContainer
: 通过ref
引用图片容器 DOM,方便后续操作。containerStyle
: 根据打印方向动态返回容器的宽高和布局样式。竖版的尺寸为 10.16cm x 15.24cm,横版的尺寸为 15.24cm x 10.16cm。imgStyle
: 控制图片在容器中的展示方式,确保图片不会超出容器并保持适当的比例。printPhoto
: 该方法首先根据用户选择的方向调整isPortrait
的值,接着使用html2canvas
将图片容器内容转换为一张图片,最后使用window.print()
打印这张合成的图片。
5. 打印效果
- 竖版(portrait): 容器宽度为 10.16 cm,高度为 15.24 cm。
- 横版(landscape): 容器宽度为 15.24 cm,高度为 10.16 cm。
6. 布局调整
根据你的需求,你可以调整 containerStyle
中的 flexDirection
和 justifyContent
等属性来实现图片的不同排列方式。如果需要特定的排列方式(例如 2x2 网格),可以调整 flex-wrap
、grid
或者其他 CSS 布局技术。