目錄
一、效果展示
二、插件推薦與引入
三、代碼具體應用
四、h5端將base64轉換為url
一、效果展示
二、插件推薦與引入
手寫板、簽字板;<zwp-draw-pad /> - DCloud 插件市場
這個在微信小程序引入時內容簡單,且涉及的方法很多,可滿足撤銷、刪除、保存、畫筆顏色修改等操作。其中保存的圖片結果是base64,可借助微信小程序的轉換方法將其轉換為url臨時地址。
三、代碼具體應用
<view class="content"><zwp-draw-pad :width="w" :height="h" ref="drawPad" /><view class="sa" @click="onCancel()">撤銷</view><view class="sa" @click="onSave()">保存</view><view class="sa" @click="onClear()">清除</view></view>
<script>
import { base64src } from "../../utils/base64src.js"; // 后面引用路徑為base64src.js文件路徑export default {data() {return {w: 375,h: 375,}},methods: {onSave() {this.$refs.drawPad.save().then(res => {console.log('保存圖片的地址', res.tempFilePath)base64src( res.tempFilePath, (res) => {console.log(res); // 轉換后的臨時連接路徑});})},onCancel() {this.$refs.drawPad.back()},onClear() {this.$refs.drawPad.init()this.$refs.drawPad.clearCache()},}}
</script>
其中通過this.$refs.drawPad.originData.length 是否>0來判斷是否在畫板上進行了簽名!
借助工具函數,使用引入即可!
const base64src = (base64data, fun) => {const base64 = base64data; //base64格式圖片const time = new Date().getTime();const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "share" + ".png";//如果圖片字符串不含要清空的前綴,可以不執行下行代碼.const imageData = base64.replace(/^data:image\/\w+;base64,/, "");const file = wx.getFileSystemManager();file.writeFileSync(imgPath, imageData, "base64");fun(imgPath);
};
export { base64src };
四、h5端將base64轉換為url
base64ImgtoFile (dataurl, filename = 'file') { const arr = dataurl.split(',')const mime = arr[0].match(/:(.*?);/)[1]const suffix = mime.split('/')[1]const bstr = atob(arr[1])let n = bstr.lengthconst u8arr = new Uint8Array(n)while (n--) { u8arr[n] = bstr.charCodeAt(n)}return new File([u8arr], `${ filename}.${ suffix}`, { type: mime})},
let file = this.getBase64ImageUrl(res.tempFilePath) // 得到File對象(res.tempFilePath即為base64形式)
this.imgUrl = window.webkitURL.createObjectURL(file) || window.URL.createObjectURL(file) // imgUrl圖片網絡路徑