1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > h5如何实现页面生成海报 保存图片及分享到微信/朋友圈功能

h5如何实现页面生成海报 保存图片及分享到微信/朋友圈功能

时间:2018-09-04 01:16:33

相关推荐

h5如何实现页面生成海报    保存图片及分享到微信/朋友圈功能

知识点:

使用html2canvas实现移动端H5页面截图实现canvas图片转为文件阿里云文件上传功能.……HTMLCanvasElement.toDataURL()DataURL与File,Blob,canvas对象之间的互相转换的Javascript

template:

<template><div class="letter_box" id="shareContainer" :style="{ height: height ? height + 'px' : '100vh' }"><!-- 头部logo --><div class="header" v-show="isShowHeader" id="header"><div class="logo_box"><img src="@/common/images/logo@2x.png" alt="" /></div></div><div class="main"><!-- 重新播放 & 分享按钮 --><div id="share_outer" v-if="isShowShareBtn" class="share_outer"><img src="@/common/imgs/17-replay@2x.png" alt="" @click="replay" /><img src="@/common/imgs/17-share@2x.png" alt="" @click="handleShare" /></div><!-- 二维码区域 --><div class="rqcode_box" v-show="isShowRqcode" id="rqcode_box"><div class="rqcode"><img src="@/common/imgs/xh_code.png" alt="" /></div><div class="rqword"><p class="lh33">扫一扫</p><p class="lh33">查收你的个人年报</p></div></div></div><!-- 分享弹窗 --><van-share-sheetclass="share_box" title="" v-model="showShare":options="options" @select="onSelect" @cancel="onCancel"/></div></template>

<script>import ossUpload from '@/mixins/ossUpload'; // 没用到import html2canvas from 'html2canvas';import OSS from 'ali-oss';import { commonCall } from '@/common/js/mUtils';

export defaultv{mixins: [ossUpload], // 没用到data() {return {url: '', // 图片地址ossConfig: {},imgTypes: ['jpg', 'png', 'gif', 'bmp'],showShare: false, // 是否展示分享弹窗isShowRqcode: false, // 是否展示二维码isShowShareBtn: true, // 是否展示分享按钮isShowHeader: false, // 是否展示头部options: [{name: '保存图片',type: '2',icon:'http://nhfcloms-deveopler.oss-cn-/dwwb/portal/project/1609815463993/undefined'},{name: '微信',type: '1',icon:'http://nhfcloms-deveopler.oss-cn-/dwwb/portal/project/1609815451747/undefined'},{name: '朋友圈',type: '0',icon:'http://nhfcloms-deveopler.oss-cn-/dwwb/portal/project/1609815438058/undefined'}],}},created() {//触发获取OSS服务器的token(文件上传)this.getOssConfig();},methods:{// oss配置getOssConfig() {this.$api.getOssToken().then((res) => {this.ossConfig = {stsToken: res.body.SecurityToken,accessKeyId: res.body.AccessKeyId,accessKeySecret: res.body.AccessKeySecret,bucket: res.body.bucket,region: res.body.region.split('.')[0]};});},}}

//dataURL转化为file对象

dataURLtoFile(dataurl, filename) {let arr = dataurl.split(',');let mime = arr[0].match(/:(.*?);/)[1];let bstr = atob(arr[1]);let n = bstr.length;let u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}//转换成file对象return new File([u8arr], filename, { type: mime });//转换成成blob对象//return new Blob([u8arr],{type:mime});},

//点击分享,生成海报

handleShare() {let _this = this;// 有链接则打开弹窗if (_this.url) {this.showShare = true;return;}let client = new OSS(this.ossConfig);// 获取需要截屏的容器let id = document.getElementById('shareContainer');// loading状态this.$Toast.loading({mask: true,message: '请稍等...',duration: 0});html2canvas(id, {// 一些配置backgroundColor: null,// 有哪些页面上存在,但是不想展示在截图的海报上面的,可以ignore忽略这些元素ignoreElements: (element) => {if (element.id === 'share_outer') return true;},// 有哪些页面上隐藏了的元素,但是又想展示在截图的海报上,可以clone克隆一份使其显现出来blockonclone(doc) {let e = doc.querySelector('#rqcode_box');let ei = doc.querySelector('#header');e.style.display = 'block';ei.style.display = 'block';}}).then((canvas) => {// 在这里把canvas存起来,后面可以用,这一步不是必需this.canvas = canvas;// canvas.toDataURL(type, encoderOptions);图片格式/质量_this.base64Img = canvas.toDataURL('image/png', 1.0);// console.log(_this.base64Img)得到一个url格式为:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"let files = _this.dataURLtoFile(this.base64Img, 'shareImg');// 处理数据,用于阿里云分片上传let imgFiles = files.type.split('/')[1];let imgName;let date = new Date().getTime();_this.imgTypes.map((item) => {if (item === imgFiles) {imgName = files.name + date + '.' + item;}});// 分片上传client.multipartUpload(imgName, files).then(function(res) {let requestUrls = res.res.requestUrls[0];// 将阿里云储存地址赋值给this.url_this.url = requestUrls.split('?')[0];_this.$Toast.clear();// 展开分享弹窗_this.showShare = true;// _this.isShowRqcode = false// _this.isShowShareBtn = true}).catch(() => {_this.$Toast.fail('缺少图片分享地址!!');});});},

// 点击分享弹窗

onSelect(option) {// console.log(option);// this.showShare = false;// 下载图片if (option.type == '2') {this.$Toast.loading({mask: true,message: '请稍等...',duration: 0});this.saveImgLocal();} else {this.shareWechat(option.type);}this.$nextTick(() => {//关闭弹窗this.showShare = false;// 清除url???在哪个步骤this.url = '';});},

// 保存图片到本地saveImgLocal() {const _this = this;// 调用原生的方法this.$appBridge.callHandler('saveFile', this.url, (res) => {_this.$Toast.clear(); // 清除loading处理返回数据………………});},

// 分享到朋友/朋友圈shareWechat(type) {let _this = this;if (_this.url) {this.$toast.loading({mask: true,message: '分享中...'});commonCall('shareImage', type, _this.url, _this.shareEndFail);} else {this.$Toast.fail('缺少图片分享地址!!');}},shareEndFail() {this.$toast.clear();}

commonCall文件(与安卓和ios交互)

/* 调用原生方法 fn:定义的方法 arg:定义的参数 */export const commonCall = (fn,type,byte,errFn) => {let u = navigator.userAgent;let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端if(isAndroid) {try {window.JsBridge[fn](type,byte)} catch (err) {console.log(err)errFn()}} else if(isiOS) {try {console.log('IOS方法调用', fn,type,byte);let params = type + ',' + bytealert(params)window.webkit.messageHandlers[fn].postMessage(params,params)} catch (err) {alert(err)console.log(err)errFn()}}};

知识:

使用html2canvas实现移动端H5页面截图:步骤:

1.首先需要安装html2canvas

npm install html2canvas

2.然后在对应的vue组件的

<script>import html2canvas from 'html2canvas'</script>

3.html2canvas(document.getElementById(‘main’)这里的main包含的是你需要截屏的内容的容器的id。

<div id="main">这里面放自己想要截图的内容区,这个容器以外的内容不会截取到。</div>

4.通过事件进行触发

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。