1、先安装依赖 npm i html2canvas
2、先声明变量,用来控制大小和方向的
const exportPicture = ref(false)
const a3 = ref(
{
S:{
width:3508,
height:4961,
},
H:{
width:4961,
height:3508
}
}
)
const a4 = ref(
{
S:{
width:2480,
height:3508,
},
H:{
width:3508,
height:2480
}
}
)
const pageType = ref(1) // 1a3 2a4
const direction = ref('S') // S竖 H横
3、导出方法
function exportSeatMap(tag = 0) {
btnLoading.value = true
const fileName = props.courseName + "座位图" + (mapDirection.value === 'front' ? '[讲台在前]' : '[讲台在后]') + '.png';
html2canvas(seatMapRef.value, { // 绑在你需要打印地方的 ref="seatMapRef"
allowTaint: true,
useCORS: true
}).then(canvas => {
let final = canvas
if(tag){
// 创建新的canvas元素
let newCanvas = document.createElement("canvas");
let newContext = newCanvas.getContext("2d");
// 设置纸张尺寸
newCanvas.width = pageType.value == 1 ? a3.value[direction.value].width : a4.value[direction.value].width
newCanvas.height = pageType.value == 1 ? a3.value[direction.value].height : a4.value[direction.value].height
// 设置纸张背景颜色
newCanvas.style.background = '#fff'
// 计算缩放比例
let scaleX = newCanvas.width / canvas.width;
let scaleY = newCanvas.height / canvas.height;
let scale = Math.min(scaleX, scaleY);
// 居中处理
let centerX = 0
let centerY = 0
if(scaleX >= scaleY){
centerX = parseInt(newCanvas.width / 2) - parseInt(canvas.width * scale / 2)
}else{
centerY = parseInt(newCanvas.height / 2) - parseInt(canvas.height * scale / 2)
}
// 在新纸张上绘制原始canvas图片对象
newContext.drawImage(
canvas,
0,
0,
canvas.width,
canvas.height,
centerX,
centerY,
canvas.width * scale,
canvas.height * scale
);
final = newCanvas
}
// 下载
var link = document.createElement("a");
document.body.appendChild(link);
link.download = fileName
link.href = final.toDataURL()
link.target = '_blank';
link.click();
btnLoading.value = false
ElMessage.success('已成功导出座位图')
exportPicture.value = false
});
}
只是提供了思路方法,具体的根据自己需求修改复制代码使用。