html2canvas 绘制海报 框架uniapp

159 阅读1分钟
<!-- 海报 影藏位置 -->
			<div class="canDiv" ref="canDiv" v-show="haiBa">
				<view class="canDiv1">
					<!-- crossorigin ="anonymous" -->
					<img ref="imhBx" :src="canvasImg.img" mode=""></img>
				</view>
				<view class="canDiv2">{{canvasImg.name}}</view>
				<view class="canDiv3">
					<image :src="canvasImg.erWeima" mode=""></image>
				</view>
				<view class="canDiv4">长按图片保存到手机</view>
			</div>


            <view class="pl1" @click="shareBtn">
				<span class="iconfont foSiz20">&#xe6c4;</span>分享
			</view>

弹出层位置

<uni-popup ref="popupCan" type="center">
			<!-- <view class="" :style="{width:imgWidth,height:imgHeight}"> -->
			<view class="popImg">
				<!-- <view class="popImg" @click.stop="closeBtn"> -->
				<image class="imgPop" :src="imgsBox" mode="aspectFit" style="z-index: 1000;"></image>
			</view>
			<!-- </view> -->
		</uni-popup>
//官网地址
http://html2canvas.hertzen.com/
//微信小程序基于base64生成二维码插件地址
https://github.com/Pudon/weapp-qrcode

//安装
Install NPM
npm install --save html2canvas
Install Yarn
yarn add html2canvas
//页面引入
import html2canvas from 'html2canvas';

// 本页面二维码生成方法
import qrcode from '../../utils/weapp-qrcode.js'

//data数据
data() {
		return {
			haiBa:false,
            canvasImg: {
					img: '',
					name: '',
					erWeima: ''
				}
    }
}
onLoad(e) {

			// 生成二维码
			let erCode = window.location.href
			let params = erCode // 二维码参数
			var imgData = qrcode.drawImg(params, {
				typeNumber: 4, // 密度
				errorCorrectLevel: 'L', // 纠错等级
				size: 800, // 白色边框
			})
			this.canvasImg.erWeima = imgData
},
methods: {
            // canvas海报
			generatorImage() {
				html2canvas(this.$refs.canDiv).then(canvas => {
					// uni.showLoading({
					// 	title: '生成中...'
					// })
					// console.log("canvas", canvas.toDataURL());
					this.imgsBox = canvas.toDataURL() //base64字符串   放到图片标签上
					// uni.hideLoading()
				});
			},

			// 生成分享
			shareBtn() {
				this.haiBa = true
				uni.showLoading({
					title: '生成中...'
				})
				setTimeout(() => {
					uni.hideLoading()
					this.generatorImage()
					this.$refs.popupCan.open()
					this.haiBa = false
					
				}, 500)
			
			},
}

补充一下小程序问题,小程序中,uniapp的ref要绑定在子组件中才能被获取,如果绑定在view,是获取不了的,你得把业务写在一个组件来引用才行。h5则没有这种情况。