uniapp使用html2canvas实现PCWeb或手机H5截图

uniapp使用html2canvas实现PCWeb或手机H5截图

1、导入html2canvas

npm install --save html2canvas

2、所需页面引入

import html2canvas from 'html2canvas';

3、JS部分代码

let dom = document.querySelector('#page'); // 获取dom元素
html2canvas(dom, {
	width: dom.clientWidth, //dom 原始宽度
	height: dom.clientHeight,
	scrollY: 0, // html2canvas默认绘制视图内的页面,需要把scrollY,scrollX设置为0
	scrollX: 0,
	useCORS: true //支持跨域,但好像没什么用
}).then(canvas => {
	// 将生产的canvas转为base64图片
	let base64 = canvas.toDataURL('image/png');
	// 将base64转换为图片保存
	if (window.navigator.msSaveOrOpenBlob) {
		let bstr = atob(base64.split(',')[1]);
		let n = bstr.length;
		let u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		let blob = new Blob([u8arr]);
		window.navigator.msSaveOrOpenBlob(blob, 'pigeons-download' + '.' + 'png');
	} else {
		// 这里就按照chrome等新版浏览器来处理
		const a = document.createElement('a');
		a.href = base64;
		a.setAttribute('download', 'pigeons-download');
		a.click();
	}
});

4、html部分代码

<template>
	<view class="body">
		<top-navigation :isBack="true">
			<template #center-slot>
				<view class="title">报名详情view>
			template>
			
			<template #right-slot>
				<view class="title" @tap="clickWx">分享view>
			template>
			
		top-navigation>
		<view class="content" id="page">
			<view class="main">
				<view style="margin-bottom: 30rpx;">
					<view>比赛公棚:{{registrationDetails.bob_name}}view>
					<view>比赛名称:{{registrationDetails.match_name}}view>
					<view>报名时间开始时间:{{registrationDetails.sign_end}}view>
					<view>报名时间结束时间:{{registrationDetails.sign_start}}view>
					<view style="width: 650rpx;">
						比赛说明:
						<text class="instructions">{{registrationDetails.match_content}}text>
					view>
					<view>报名会员:{{registrationDetails.name}}view>
					<view>投注金额:¥{{registrationDetails.total_money}}view>
					<view>支付状态:{{registrationDetails.is_paid == 0 ? '待付款' : '已付款'}}view>
				view>
			view>
		view>
		<view class="bottom-btn">
			<view class="btn-box" @tap="savePic">
				保存到相册
			view>
			<view class="btn-box" style="border-top: none;" @tap="toMyRegistrationDetail">查看订单记录view>
		view>
	view>
template>

5、效果截图
uniapp使用html2canvas实现PCWeb或手机H5截图_第1张图片

你可能感兴趣的:(html5,javascript,uni-app,前端)