uniapp-原生地图截屏返回base64-进行画板编辑功能

一、场景

vue写uniapp打包安卓包,实现原生地图截屏(andirod同事做的)-画板编辑功能

实现效果:

二、逻辑步骤简略

1. 由 原生地图nvue部分,回调返回 地图截屏生成的base64 数据,

2. 通过 uni插件市场 image-tools 插件 base64ToPath方法,将base64数据 转成文件路径

3. 通过 uni -API- uni.createCanvasContext() 、ctx.createPattern() 方法,将 图片数据 创建绘图对象

4. 通过 uni - movable-area+movable-view 控制画布缩放

5. 通过 canvas @touchmove="touchmove"  @touchend="touchend"  @touchstart="touchstart" 等方法实现在画布上绘制画笔

6. 生成图片及清空画布

三、具体实现

1.  由 原生地图nvue部分,回调返回 原生地图截屏生成的base64 数据(andirod同事做的)

2.  image-tools 插件 base64ToPath 

image-tools - DCloud 插件市场

import { pathToBase64, base64ToPath } from '@/js_sdk/mmmm-image-tools/index.js'

3.通过 uni -API- uni.createCanvasContext() 、ctx.createPattern() 方法

uni-app官网 API- createPattern()

initC() {const that = this// 创建绘图对象this.ctx = uni.createCanvasContext('mycanvas', this);// 在canvas设置背景 - 入参 仅支持包内路径和临时路径const pattern = this.ctx.createPattern(this.imageUrl, 'repeat-x')this.ctx.fillStyle = patternthis.ctx.setStrokeStyle('red')this.ctx.fillRect(0, 0, this.dWidth, this.dHeight)this.ctx.draw()// 方法二  在画布上插入图片// this.img = new Image();// this.img.src = this.imageUrl;// this.img.onload = () => {//   console.log('this.img', that.img.width)//   that.ctx.drawImage(that.img, 0, 0, this.dWidth, this.dHeight)//   // that.ctx.draw()// }},

4. 通过 uni - movable-area+movable-view 控制画布缩放

<movable-area :scale-area="true" :style="{'width':windowWidth+'px','height':windowHeight+'px','backgroundColor':'#ddd','overflow':'hidden'}"><movable-view direction="all":inertia="false":out-of-bounds="false":scale-min="0.001":scale-max="4"   :scale="true":disabled="movableDisabled":scale-value="scaleValue"class="pr":style="{'width':widths+'px','height':heights+'px'}"@scale="scaleChange"><canvasid="mycanvas"canvas-id="mycanvas":style="{'width':widths+'px','height':heights+'px'}"@touchmove="touchmove"@touchend="touchend"@touchstart="touchstart"></canvas></movable-view></movable-area>

5.通过 canvas @touchmove="touchmove"  等方法实现在画布上绘制画笔

touchstart(e) {let startX = e.changedTouches[0].xlet startY = e.changedTouches[0].yif (this.scaleValue > 1) {startX = e.changedTouches[0].x / this.scaleValue;startY = e.changedTouches[0].y / this.scaleValue;} else {startX = e.changedTouches[0].x * this.scaleValue;startY = e.changedTouches[0].y * this.scaleValue;}console.log('touchstart()-x', e.changedTouches[0].x, 'scaleValue', this.scaleValue, 'startX', startX)let startPoint = { X: startX, Y: startY };this.points.push(startPoint);// 每次触摸开始,开启新的路径this.ctx.beginPath();},touchmove(e) {if (this.isEdit) {let moveX = e.changedTouches[0].xlet moveY = e.changedTouches[0].yif (this.scaleValue > 1) {moveX = e.changedTouches[0].x / this.scaleValue;moveY = e.changedTouches[0].y / this.scaleValue;} else {moveX = e.changedTouches[0].x * this.scaleValue;moveY = e.changedTouches[0].y * this.scaleValue;}console.log('touchmove()-x', e.changedTouches[0].x, 'scaleValue', this.scaleValue, 'moveX', moveX)let movePoint = { X: moveX, Y: moveY };this.points.push(movePoint); // 存点let len = this.points.length;if (len >= 2) {this.draw(); // 绘制路径}}},touchend() {this.points = [];},draw() {let point1 = this.points[0];let point2 = this.points[1];this.points.shift();this.ctx.moveTo(point1.X, point1.Y);this.ctx.lineTo(point2.X, point2.Y);this.ctx.stroke();this.ctx.draw(true);},

6.生成图片及清空画布

clear() {let that = this;this.scaleValue = 1this.isEdit = falsethis.movableDisabled = falseuni.getSystemInfo({success: function(res) {let canvasw = res.windowWidth;let canvash = res.windowHeight;that.ctx.clearRect(0, 0, canvasw, canvash);const pattern = that.ctx.createPattern(that.imageUrl, 'repeat-x')that.ctx.fillStyle = patternthat.dWidth = 285that.dHeight = 200that.ctx.setStrokeStyle('red')that.ctx.fillRect(0, 0, that.dWidth, that.dHeight)that.ctx.draw()// that.ctx.draw(true);}});},finish() {let that = this;uni.canvasToTempFilePath({canvasId: 'mycanvas',success: function(res) {// 这里的res.tempFilePath就是生成的签字图片// console.log('tempFilePath', res.tempFilePath);that.tempFilePath = res.tempFilePaththat.$emit('onImgUrl', that.tempFilePath) // 向父级组件传值}});},

utils:

// 是否是 base64数据
export function isBase64Two(str) {try {return btoa(atob(str)) === str;} catch (err) {return false;}
}
export function isBase64(str) {// 正则表达式匹配B4-64编码格式const regex = /^[a-zA-Z0-9+\/]+={0,2}$/;return regex.test(str);
}
// 校验内容是否包含base64格式的图片
export function isBase64Three(str){let imgReg = RegExp(/data:image\/.*;base64,/)const res = imgReg.test(str)return res
}

四、总结

以下完整代码 DrawingBoard.vue:

<template><view class="canvas-frame"><view class="icon-frame"><uni-icons :class="{ 'is-edit': isEdit }" type="compose" size="18" class="icon-item mr10" @click="createCanvas">编辑</uni-icons><uni-iconstype="plus"size="18" class="icon-item mr10"title="放大"@click="plusImageScalex"></uni-icons><uni-iconstype="minus"size="18" class="icon-item"title="缩小"@click="minusImageScalex"></uni-icons></view><view class="button-frame"><button size="mini" class="mr10" @click="clear">清空</button><button size="mini" @click="finish">确定</button></view><!-- style="border: 1rpx solid #ccc;width: 570rpx; height: 400rpx;" --><!-- <canvasid="mycanvas"canvas-id="mycanvas":style="{'width':widths+'px','height':heights+'px'}"@touchmove="touchmove"@touchend="touchend"@touchstart="touchstart"></canvas> --><movable-area :scale-area="true" :style="{'width':windowWidth+'px','height':windowHeight+'px','backgroundColor':'#ddd','overflow':'hidden'}"><movable-view direction="all":inertia="false":out-of-bounds="false":scale-min="0.001":scale-max="4"   :scale="true":disabled="movableDisabled":scale-value="scaleValue"class="pr":style="{'width':widths+'px','height':heights+'px'}"@scale="scaleChange"><canvasid="mycanvas"canvas-id="mycanvas":style="{'width':widths+'px','height':heights+'px'}"@touchmove="touchmove"@touchend="touchend"@touchstart="touchstart"></canvas></movable-view></movable-area></view>
</template><script>
// import { fabric } from 'fabric';
// import { fabric } from '@/utils/fabric.min.js';
// import { Database64ToFile } from '@/utils/index';
import { pathToBase64, base64ToPath } from '@/js_sdk/mmmm-image-tools/index.js'
import { isBase64 } from '@/utils/index.js';
// isBase64 方法判断 原生端返回到的数据格式是否正确
export default {props: {// 更新 原始地图画布mapImageUrl: {type: String,default: '',}},data() {return {canvasEle: null,isEdit: false,imageContainer: null,scaleValue: 1,ctx: '', // 绘图图像points: [], // 路径点集合tempFilePath: '', // 签名图片imageUrl: require('@/static/res/imgs/all/fushanhou-area.jpg'), // 本地图片画布资源img: null,dWidth: 285,dHeight: 200,widths: 285,heights: 200,windowWidth: 285,windowHeight: 200,movableDisabled: false,};},mounted() {this.initC()},watch: {mapImageUrl(newV, oldV) {const that = thisconsole.log('watch()-mapImageUrl-newV,监听数据变化-newV', newV? '有值': '无值')if (!['',undefined,null].includes(newV)) {console.log('watch()-mapImageUrl-isBase64(newV)', isBase64(newV))// const base64Image = 'data:image/png;base64,/9j/4AAQSkZJRgA...'; // that.base64ToTempFilePath(newV ,(tempFilePath) => {//   console.log('转换成功,临时地址为:', tempFilePath)//   that.imageUrl = tempFilePath //   // 会在canvas中调用//   that.initC()// }, // () =>{//   console.log('fail转换失败')// });const base64 = 'data:image/png;base64,' + newV;base64ToPath(base64).then((tempFilePath) => {console.log('转换成功,临时地址为:', tempFilePath)that.imageUrl = tempFilePaththat.initC()})}},},methods: {initC() {const that = this// 创建绘图对象this.ctx = uni.createCanvasContext('mycanvas', this);// 在canvas设置背景 - 入参 仅支持包内路径和临时路径const pattern = this.ctx.createPattern(this.imageUrl, 'repeat-x')this.ctx.fillStyle = patternthis.ctx.setStrokeStyle('red')this.ctx.fillRect(0, 0, this.dWidth, this.dHeight)this.ctx.draw()// 方法二  在画布上插入图片// this.img = new Image();// this.img.src = this.imageUrl;// this.img.onload = () => {//   console.log('this.img', that.img.width)//   that.ctx.drawImage(that.img, 0, 0, this.dWidth, this.dHeight)//   // that.ctx.draw()// }},createCanvas() {this.isEdit = !this.isEditif (this.isEdit) {this.movableDisabled = true// 设置画笔样式this.ctx.lineWidth = 2;this.ctx.lineCap = 'round';this.ctx.lineJoin = 'round';} else {this.movableDisabled = false}},touchstart(e) {let startX = e.changedTouches[0].xlet startY = e.changedTouches[0].yif (this.scaleValue > 1) {startX = e.changedTouches[0].x / this.scaleValue;startY = e.changedTouches[0].y / this.scaleValue;} else {startX = e.changedTouches[0].x * this.scaleValue;startY = e.changedTouches[0].y * this.scaleValue;}console.log('touchstart()-x', e.changedTouches[0].x, 'scaleValue', this.scaleValue, 'startX', startX)let startPoint = { X: startX, Y: startY };this.points.push(startPoint);// 每次触摸开始,开启新的路径this.ctx.beginPath();},touchmove(e) {if (this.isEdit) {let moveX = e.changedTouches[0].xlet moveY = e.changedTouches[0].yif (this.scaleValue > 1) {moveX = e.changedTouches[0].x / this.scaleValue;moveY = e.changedTouches[0].y / this.scaleValue;} else {moveX = e.changedTouches[0].x * this.scaleValue;moveY = e.changedTouches[0].y * this.scaleValue;}console.log('touchmove()-x', e.changedTouches[0].x, 'scaleValue', this.scaleValue, 'moveX', moveX)let movePoint = { X: moveX, Y: moveY };this.points.push(movePoint); // 存点let len = this.points.length;if (len >= 2) {this.draw(); // 绘制路径}}},touchend() {this.points = [];},draw() {let point1 = this.points[0];let point2 = this.points[1];this.points.shift();this.ctx.moveTo(point1.X, point1.Y);this.ctx.lineTo(point2.X, point2.Y);this.ctx.stroke();this.ctx.draw(true);},clear() {let that = this;this.scaleValue = 1this.isEdit = falsethis.movableDisabled = falseuni.getSystemInfo({success: function(res) {let canvasw = res.windowWidth;let canvash = res.windowHeight;that.ctx.clearRect(0, 0, canvasw, canvash);const pattern = that.ctx.createPattern(that.imageUrl, 'repeat-x')that.ctx.fillStyle = patternthat.dWidth = 285that.dHeight = 200that.ctx.setStrokeStyle('red')that.ctx.fillRect(0, 0, that.dWidth, that.dHeight)that.ctx.draw()// that.ctx.draw(true);}});},finish() {let that = this;uni.canvasToTempFilePath({canvasId: 'mycanvas',success: function(res) {// 这里的res.tempFilePath就是生成的签字图片// console.log('tempFilePath', res.tempFilePath);that.tempFilePath = res.tempFilePaththat.$emit('onImgUrl', that.tempFilePath)}});},plusImageScalex() {const num = this.scaleValue + 0.4this.scaleValue = Math.floor(num * 100) / 100;// this.setImageScale(this.scaleValue);},minusImageScalex() {const num = this.scaleValue + 0.4this.scaleValue = - (Math.floor(num * 100) / 100);// this.setImageScale(-this.scaleValue);},// 设置图片缩放setImageScale(scale) {const that = thisconsole.log('this.ctx.', this.ctx.dWidth, scale)// const value = this.imageContainer.scaleX + scale;// const zoom = Number(value.toFixed(2));// // 设置图片的缩放比例和位置// this.imageContainer.set({//   scaleX: zoom,//   scaleY: zoom,// });// this.canvasEle.renderAll();// that.ctx.fillRect(0, 0, 285, 200)// that.ctx.draw()const pattern = that.ctx.createPattern(that.imageUrl, 'repeat-x')that.ctx.fillStyle = patternconst w = that.dWidth * scale const h = that.dHeight * scaleconsole.log('this.ctx.',w, h)that.ctx.fillRect(0, 0, w, h)that.ctx.draw()},//点击事件 判断缩放比例 touchstart(e) {let x = e.touches[0].xlet y = e.touches[0].y// this.node.forEach(item => {//   if (x > item.x * this.scale && x < (item.x + item.w) * this.scale//       && y > item.y * this.scale && y < (item.y + item.h) * this.scale) {//       //在范围内,根据标记定义节点类型//       // this.lookDetial(item)//   }// }) },//s缩放比例scaleChange(e) {this.scaleValue = e.detail.scale},// 将base64图片转换为临时地址base64ToTempFilePath(base64Data, success, fail) {const fs = uni.getFileSystemManager()const fileName = 'temp_image_' + Date.now() + '.png' // 自定义文件名,可根据需要修改const USER_DATA_PATH = 'ttfile://user' // uni.env.USER_DATA_PATHconst filePath = USER_DATA_PATH + '/' + fileNameconst buffer = uni.base64ToArrayBuffer(base64Data)fs.writeFile({filePath,data: buffer,encoding: 'binary',success() {success && success(filePath)},fail() { fail && fail()}});},// base64转化成本地文件路径parseBlob(base64, success) {const arr = base64.split(',');console.log('parseBlob()-arr:', arr)const mime = arr[0].match(/:(.*?);/)[1];const bstr = atob(arr[1]);const n = bstr.length;const u8arr = new Uint8Array(n);for(let i = 0; i < n; i++) {u8arr[i] = bstr.charCodeAt(i);}// const url = URL || webkitURL;let a = new Blob([u8arr], {type: mime});const file = new File([a], 'test.png', {type: 'image/png'});console.log('parseBlob()-file', file);success && success(file)},}
};
</script><style lang="scss" scoped>
.pr{position: relative;
}
.canvas-frame {position: relative;width: 570rpx;// overflow: hidden;.icon-frame {position: absolute;top: 20rpx;right: 40rpx;z-index: 2;}.blockS{background: transparent;width: 570rpx; height: 400rpx;position: absolute;top: 0;left: 0;z-index: 1;}.icon-item {// font-size: 36rpx;// padding: 12rpx;// border-radius: 8rpx;// margin-right: 16rpx;// border: 1rpx solid #ccc;// background-color: #fff;&:hover {// background-color: #f1f1f1;}&:active {opacity: 0.8;}}.is-edit {color: #007EF3 !important;}.button-frame {position: absolute;bottom: 10rpx;right: 40rpx;z-index: 2;}#canvasElement {cursor: pointer;}
}
</style>

由于hbuildex-真机调试-打印很费劲,需要来回构建打包,从而找问题找了好久,其中因为 原生地图截屏返回的是纯base64的数据,未带 data:image\/.*;base64,然后找了半天的问题,需要一步步的推导和确认有没有错,错在那,花费了很多时间和精力;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/61308.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【pinia】Pinia入门和基本使用:

文章目录 一、 什么是pinia二、 创建空Vue项目并安装Pinia1. 创建空Vue项目2. 安装Pinia并注册 三、 实现counter四、 实现getters五、 异步action六、 storeToRefs保持响应式解构七、基本使用&#xff1a;【1】main.js【2】store》index.js【3】member.ts 一、 什么是pinia P…

flink如何监听kafka主题配置变更

背景&#xff1a; 从前一篇文章我们知道flink消费kafka主题时是采用的手动assign指定分区的方式&#xff0c;这种消费方式是不处理主题的rebalance操作的&#xff0c;也就是消费者组中即使有消费者退出或者进入也是不会触发消费者所消费的分区的&#xff0c;那么疑问就来了&am…

PHP实现在线进制转换器,10进制,2、4、8、16、32进制转换

1.接口文档 2.laravel实现代码 /*** 进制转换计算器* return \Illuminate\Http\JsonResponse*/public function binaryConvertCal(){$ten $this->request(ten);$two $this->request(two);$four $this->request(four);$eight $this->request(eight);$sixteen …

Redis的AOF持久化

除了RDB持久化功能之外&#xff0c;Redis还提供了AOF持久化功能。与RDB 持久化通过保存数据库中的键值对来记录数据库状态不同&#xff0c;AOF持久化是通过保存Redis服务器所执行的写命令来记录数据库状态的&#xff0c;如下图所示。 举个例子&#xff0c;如果我们对空白的数据…

什么是DNS欺骗及如何进行DNS欺骗

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、什么是 DNS 欺骗&#xff1f;二、开始1.配置2.Ettercap启动3.操作 总结 前言 我已经离开了一段时间&#xff0c;我现在回来了&#xff0c;我终于在做一个教…

Centos8上加速git clone

首先通过命令获取域名对应的IP地址 [rootggbond ~]# nslookup github.global.ssl.fastly.net [rootggbond ~]# nslookup github.com 之后如上获取到的IP地址 以IP-域名的格式加入到hosts文件中 [rootggbond ~]# vim /etc/hosts Centos8上更新DNS缓存 [rootggbond ~]# nscd -…

Java课题笔记~ HTTP协议(请求和响应)

Servlet最主要的作用就是处理客户端请求&#xff0c;并向客户端做出响应。为此&#xff0c;针对Servlet的每次请求&#xff0c;Web服务器在调用service()方法之前&#xff0c;都会创建两个对象 分别是HttpServletRequest和HttpServletResponse。 其中HttpServletRequest用于封…

腾讯云香港服务器租用价格_CN2线路延迟速度测试

腾讯云香港服务器&#xff0c;目前中国香港地域轻量应用服务器可选配置2核2G20M、2核2G30M、2核4G30M&#xff0c;操作系统可选Windows和Linux&#xff0c;不只是香港云服务器&#xff0c;新加坡、硅谷、法兰克福和东京服务器均有活动&#xff0c;腾讯云服务器网分享腾讯云境外…

Node.js学习笔记-03

七、网络编程 1. 构建 TCP 服务 TCP 是面向连接的协议&#xff0c;显著特征 在传输之前需要3次握手形成会话。 客户端 ——请求连接——> 服务器端 ——响应——> 客户端 ——开始传输——> 服务器端。 2. 构建 UDP 服务 3. 构建 HTTP 服务 http模块 在node中HTT…

dotNet 之数据库sqlite

Sqlite3是个特别好的本地数据库&#xff0c;体积小&#xff0c;无需安装&#xff0c;是写小控制台程序最佳数据库。NET Core是同样也是.NET 未来的方向。 **硬件支持型号 点击 查看 硬件支持 详情** DTU701 产品详情 DTU702 产品详情 DTU801 产品详情 DTU802 产品详情 D…

pythonocc进阶学习:投影projection

1.点 到 线,&#xff08;直线,曲线&#xff09;等上的投影 staticmethod # 点到Lin的投影 def Project_Pnt_To_Lin(p: gp_Pnt, lin: gp_Lin):Edge BRepBuilderAPI_MakeEdge(lin).Edge()curve BRep_Tool.Curve(Edge)proPnt GeomAPI_ProjectPointOnCurve(p, curve[0])Neares…

基于Java+SpringBoot+Vue的数码论坛系统设计与实现(源码+LW+部署文档等)

博主介绍&#xff1a; 大家好&#xff0c;我是一名在Java圈混迹十余年的程序员&#xff0c;精通Java编程语言&#xff0c;同时也熟练掌握微信小程序、Python和Android等技术&#xff0c;能够为大家提供全方位的技术支持和交流。 我擅长在JavaWeb、SSH、SSM、SpringBoot等框架…