一、場景
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,然后找了半天的問題,需要一步步的推導和確認有沒有錯,錯在那,花費了很多時間和精力;