- 這里實現是使用的mini-smooth-signature插件,可以在npm官網中進行搜索到
- 首先使用canvas標簽,下面的兩個屬性是必須的,要不然獲取節點,獲取不到
<canvas type="2d" id="myCanvas"></canvas>
<view class="canvas-sign">
<canvas
type="2d"
id="signature1"
class="signature1"
style="width:{{width}}px;height:{{height}}px;"
disable-scroll="{{true}}"
bindtouchstart="handleTouchStart1"
bindtouchmove="handleTouchMove1"
bindtouchcancel="handleTouchEnd1"
bindtouchend="handleTouchEnd1"
></canvas>
<view class="actions1">
<button bindtap="handleClear1">
清除
</button>
<button bindtap="handleUndo1">
撤銷
</button>
<button bindtap="handlePreview1">
生成圖片
</button>
<button bindtap="handleColor1">
修改顏色
</button>
</view>
</view>
/* 樣例1 */
.container1 {
text-align: center;
}
.signature1 {
margin: 25px auto;
border: 2rpx solid #eee;
}
.actions1 {
margin-top: 20px;
text-align: center;
}
.actions1 button {
display: inline-block;
height: 30px;
line-height: 30px;
padding: 0 10px;
}
- js canvas的寬度,高度是必填的,否則也獲取不到節點信息
import Signature from '../../utils/index'
Component({
/**
* 組件的屬性列表
*/
properties: {
width: {
type: Number,
value: 400
},
height:{
type: Number,
value: 728
},
color:{
type:String,
value:'000'
},
bgColor:{
type:String,
value:'#eee'
},
textList:{
type:Array,
value:[]
},
pixelRatio:{
type: Number,
value: 1
}
},
/**
* 組件的初始數據
*/
data: {
},
pageLifetimes:{
show(){
this.initCanvas()
},
},
/**
* 組件的方法列表
*/
methods: {
//初始化函數
initCanvas: function () {
const query = wx.createSelectorQuery().in(this)
query.select('#signature1').fields({ node: true, size: true }).exec(res=>{
console.log(res,'節點信息');
const canvas = res[0].node
const ctx = canvas.getContext('2d')
canvas.width = +this.data.width * +this.data.pixelRatio
canvas.height = +this.data.height * +this.data.pixelRatio;
this.signature1 = new Signature(ctx, {
width: +this.data.width,
height: +this.data.height,
scale: +this.data.pixelRatio,
textList: this.data.textList,
// textList:[//上下添加文本
// {x:0,y:20,text:'hello',center:'start',color: this.data.color},
// {x:200,y:200,text:'底部1111',center:'start',color: this.data.color}
// ],
color:this.data.color,
// bgColor: this.data.bgColor,//背景色跟添加文本有沖突,兩者取其一
toDataURL: (type, quality) => canvas.toDataURL(type, quality),
requestAnimationFrame: (fn) => canvas.requestAnimationFrame(fn),
getImagePath: () => new Promise((resolve, reject) => {
const img = canvas.createImage();
img.onerror = reject;
img.onload = () => resolve(img);
img.src = canvas.toDataURL();
})
})
})
},
//開始
handleTouchStart1(e) {
const pos = e.touches[0];
this.signature1.onDrawStart(pos.x, pos.y);
},
// 移動
handleTouchMove1(e) {
const pos = e.touches[0];
this.signature1.onDrawMove(pos.x, pos.y);
},
// 結束
handleTouchEnd1() {
this.signature1.onDrawEnd();
},
//清空
handleClear1() {
this.signature1.clear();
},
//撤銷
handleUndo1() {
this.signature1.undo();
},
//修改顏色
handleColor1() {
this.signature1.color = '#' + Math.random().toString(16).slice(-6);
},
//確認,簽名后生成圖片
handlePreview1() {
if (this.signature1.isEmpty()) {
wx.showToast({ icon: 'none', title: '未簽名' });
return;
}
const dataURL = this.signature1.toDataURL();
this.base64ToPath(dataURL).then(url => {
// wx.compressImage({
// })
url&& this.triggerEvent("signUrl",{url})
});
},
// base64轉本地
base64ToPath(dataURL) {
return new Promise((resolve, reject) => {
const data = wx.base64ToArrayBuffer(dataURL.replace(/^data:image\/\w+;base64,/, ""));
const filePath = `${wx.env.USER_DATA_PATH}/${Math.random().toString(32).slice(2)}.png`;
wx.getFileSystemManager().writeFile({
filePath,
data,
encoding: 'base64',
success: () => resolve(filePath),
fail: reject,
});
})
},
}
})
- 在使用組件進行傳參的時候,需要加個條件判斷下,否則渲染太快導致頁面的布局有問題
- 使用組件的js頁面
// packageH/pages/signature/signature.js
Page({
/**
* 頁面的初始數據
*/
data: {
width1: '',
height1: '',
pixelRatio: ''
},
signUrl(e){
console.log(e);
if(e.detail.url){
wx.setStorageSync('canvasSign', e.detail.url)
wx.navigateBack({
delta: 1,
})
}
},
/**
* 生命周期函數--監聽頁面加載
*/
onLoad(options) {
const { windowWidth, windowHeight, pixelRatio } = wx.getSystemInfoSync()
this.setData({
width1: windowWidth-14,
height1: windowHeight-140,
pixelRatio
})
},
})
<view class="canvas-sign">
<view class="title">
請手寫簽名:
</view>
<!-- 這里需要加個條件判斷下,否則組件的渲染有問題-->
<block wx:if="{{width1}}">
<canvas-sign bind:signUrl="signUrl" width="{{width1}}" height="{{height1}}" pixelRatio="{{pixelRatio}}"></canvas-sign>
</block>
</view>
{
"usingComponents": {
"canvas-sign":"../../../components/canvasSign/canvasSign"
},
"navigationBarTitleText": "簽名"
}
- 不想使用插件,也可以自己使用canvas進行寫,很簡單的,具體可以參考我的另一篇h5使用canvas進行繪制的這篇文章
小程序中使用canvas寫的進行適配
// 文字換行
drawtext(ctx,t,x,y,w){
//參數說明
t = t.split('');
let tL = Math.ceil(t.length / 16);
console.log(tL,'幾行',t,t.length);
for(let i = 0; i < tL ; i++){
y = i > 0 ? y+30 : y
ctx.fillText( t.join('').substr(i*16,16),x,y,w);//每行字體y坐標間隔20
console.log(' arr.slice(i*16,16)', t.join('').substr(i*16,16),y,t);
}
return y
},
- 標題下面的y坐標使用上面的函數導出的y坐標進行加一個固定值就可以
- canvas的寬度使用獲取屏幕的寬度就可以
- 將rpx單位轉px
const { windowWidth, windowHeight, pixelRatio } = wx.getSystemInfoSync()
const px = (rpx)=>rpx / 375 * windowWidth
注意:在使用canvas生成圖片之后,圖片的路徑是base64的格式,上面有使用 wx.getFileSystemManager().writeFile這個api進行轉為本地路徑的圖片格式,但是這個有的用戶手機上會有問題,微信環境中會報錯,提示storage超出限制,最后沒有辦法,直接將base64傳遞給后臺,讓后臺進行轉化(可能你會問,為啥不能直接base64的形式上傳圖片,這個是wx.upload這個api的限制,需要本地路徑,不支持base64),或者使用 wx.canvasToTempFilePath這個api,最新的canvas - api用不了這個