详细查看界面长截图 view截图 截屏
注:图片需要转Base64
如果项目没有npm的支持,首先 npm init -y
引入html2Canvas的依赖,注意版本号为【1.0.0-rc.4】执行 npm install --save html2canvas@1.0.0-rc.4
index.vue
<template>
<view>
<longScreen ref="html2canvas" :domId="domId" @renderFinish="renderFinish">
<view id="poster">
<view v-for="count in 10">{{count}}view>
view>
longScreen>
<view style="margin-top: 100px;">
<button @click="createPoster()">生成海报button>
view>
<view v-if="posterImgFilePath.length>0">
<view class="poster-view">
<image :src="posterImgFilePath" mode="scaleToFill"
:style="'width:'+(posterWidth-30)+'px;height:'+(posterHeight-50)+'px;'">image>
view>
view>
view>
template>
<script>
import longScreen from "@/components/longScreenShot/longScreenShot.vue"
import {
base64ToPath,
pathToBase64
} from '@/utils/image-tools.js';
export default {
components: {
longScreen
},
data() {
return {
domId: 'poster', //要生成截图的Dom的ID,用于获取文档内的html
posterImgFilePath: '', //生成的图片路径
posterWidth: 0, //生成的图片宽度
posterHeight: 0, //生成的图片高度
}
},
methods: {
//开始生成海报
createPoster: function() {
this.domId = '#poster' + (new Date().getTime());
},
//生成的图片回响内容
renderFinish(imgObj) {
console.log("imgObj", imgObj);
this.posterImgFilePath = imgObj.posterPath;
this.posterHeight = imgObj.posterHeight;
this.posterWidth = imgObj.posterWidth;
uni.showToast({
title: "success !",
icon: 'success'
})
},
}
}
script>
<style lang="scss">
.content {
padding: 30rpx;
border: 1px solid #909399;
.conten-item {
height: 100px;
text-align: center;
margin-bottom: 20px;
background-color: #F0AD4E;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.test-image {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
margin: 20px 0px;
background-color: #4CD964;
padding: 20px;
}
}
.poster-view {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 20px 0px;
}
style>
image-tools.js
function getLocalFilePath(path) {
if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
return path
}
if (path.indexOf('file://') === 0) {
return path
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path)
if (localFilePath !== path) {
return localFilePath
} else {
path = path.substr(1)
}
}
return '_www/' + path
}
export function pathToBase64(path) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
if (typeof FileReader === 'function') {
var xhr = new XMLHttpRequest()
xhr.open('GET', path, true)
xhr.responseType = 'blob'
xhr.onload = function() {
if (this.status === 200) {
let fileReader = new FileReader()
fileReader.onload = function(e) {
resolve(e.target.result)
}
fileReader.onerror = reject
fileReader.readAsDataURL(this.response)
}
}
xhr.onerror = reject
xhr.send()
return
}
var canvas = document.createElement('canvas')
var c2x = canvas.getContext('2d')
var img = new Image
img.onload = function() {
canvas.width = img.width
canvas.height = img.height
c2x.drawImage(img, 0, 0)
resolve(canvas.toDataURL())
canvas.height = canvas.width = 0
}
img.onerror = reject
img.src = path
return
}
if (typeof plus === 'object') {
plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
entry.file(function(file) {
var fileReader = new plus.io.FileReader()
fileReader.onload = function(data) {
resolve(data.target.result)
}
fileReader.onerror = function(error) {
reject(error)
}
fileReader.readAsDataURL(file)
}, function(error) {
reject(error)
})
}, function(error) {
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: function(res) {
resolve('data:image/png;base64,' + res.data)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
export function base64ToPath(base64, extName) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64[0].match(/:(.*?);/)[1]
var str = atob(base64[1])
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array[n] = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
}
var fileName;
if (!extName) {
extName = base64.match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
fileName = Date.now() + '.' + extName;
} else {
fileName = Date.now() + extName;
}
if (typeof plus === 'object') {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, function() {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, function() {
bitmap.clear()
resolve(filePath)
}, function(error) {
bitmap.clear()
reject(error)
})
}, function(error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
longScreenShot.vue
<template>
<view>
<view :prop="domId" :change:prop="html2canvas.emitData" class="html2canvas">
<slot>slot>
view>
view>
template>
<script>
import { base64ToPath } from '@/utils/image-tools.js';
export default {
props: {
domId: {
type: String,
required: true
}
},
mounted:function(){
console.log("组件加载完成");
},
methods: {
// 接收renderjs发回的数据
async receiveRenderData(imgData) {
let posterHeight=imgData.height;
let posterWidth=imgData.width;
let imgPath =await base64ToPath(imgData.imgVal, '.jpeg');
this.$emit('renderFinish', {"posterPath":imgPath,"posterHeight":posterHeight,"posterWidth":posterWidth});
uni.hideLoading();
},
showLoading() {
uni.showLoading({
title: "正在生成导出",
icon: "none",
mask: true,
duration: 3000
})
},
hideLoading() {
uni.hideLoading();
}
}
}
script>
<script module="html2canvas" lang="renderjs">
import html2canvas from 'html2canvas';
export default {
data() {
return {
}
},
mounted:function(){
console.log("视图层渲染完成");
},
methods: {
// 发送数据到逻辑层,下面这里最好是加一个settimeout延迟,因为主界面数据还没加载渲染完成
emitData(domId) {
const dom = document.getElementById('poster');
if(!dom)return;
this.$ownerInstance.callMethod('showLoading', true);
console.log("dom",dom);
let width= dom.offsetWidth;
let height=dom.offsetHeight;
let windowHeight= uni.getSystemInfoSync().windowHeight;
let windowWidth=uni.getSystemInfoSync().windowWidth;
html2canvas(dom, {
width:width,
height:height,
//scale:2.5, // 缩放倍数
scrollY: -dom.offsetTop, // html2canvas默认绘制视图内的页面,需要把scrollY,scrollX设置为0
scrollX: -dom.offsetLeft,
x:0,
y:0,
windowWidth:windowWidth,
windowHeight:windowHeight,
useCORS: true, //支持跨域,但好像没什么用
}).then((canvas) => {
let imgVal= canvas.toDataURL('image/png');
this.$ownerInstance.callMethod('receiveRenderData',{imgVal:imgVal,height:height,width:width});
});
}
}
};
script>
<style lang="scss">
style>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)