這篇文章主要介紹了微信小程序怎么實現簡單手寫簽名組件的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇微信小程序怎么實現簡單手寫簽名組件文章都會有所收獲,下面我們一起來看看吧。
可以實現用戶在微信小程序上手寫簽名。
需要組件化。

在微信小程序中,我們使用canvas組件實現。將用戶的輸入想象成為一只筆。我們要畫的簽名是由很多點構成的。但是單純的點是不能很好地構成線。點與點之間還要由線連接。下面是實現過程代碼。
wxml
這里的canvas組件是最新的用法。
<view class="dashbox">
<view class="btnList">
<van-button size="small" bind:click="clearCanvas">清空</van-button>
</view>
<view class="handCenter">
<canvas
class="handWriting"
disable-scroll="{{true}}"
id="handWriting"
bindtouchstart="scaleStart"
bindtouchmove="scaleMove"
bindtouchend="scaleEnd"
bindtap="mouseDown"
type="2d"
>
</canvas>
</view>
</view>wxss
.btnList{
width: 95%;
margin:0 auto;
}
.handWriting{
background: #fff;
width: 95%;
height: 80vh;
margin:0 auto
}由于是在自定義組件中使用,所以要注意獲取canvas的時候的this指向問題。如果不調用SelectorQuery的In方法,那么就在自定義組件獲取不到canvas,因為這個時候指向的父組件。
Component({
/**
* 組件的初始數據
*/
data: {
canvasName:"#handWriting",
ctx:"",
canvasWidth:0,
canvasHeight:0,
startPoint:{
x:0,
y:0,
},
selectColor: "black",
lineColor: "#1A1A1A", // 顏色
lineSize: 1.5, // 筆記倍數
radius:5,//畫圓的半徑
},
ready(){
let canvasName = this.data.canvasName;
let query = wx.createSelectorQuery().in(this);//獲取自定義組件的SelectQuery對象
query.select(canvasName)
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext("2d");
//獲取設備像素比
const dpr = wx.getSystemInfoSync().pixelRatio;
//縮放設置canvas畫布大小,防止筆跡錯位
canvas.width = res[0].width * dpr;
canvas.height = res[0].height * dpr;
ctx.scale(dpr, dpr);
ctx.lineJoin="round";
this.setData({ctx});
});
query.select(".handCenter").boundingClientRect(rect => {
console.log("rect", rect);
this.setData({
canvasWidth:rect.width,
canvasHeight:rect.height
});
}).exec();
},
//省略以下代碼......
});Component({
//省略以上代碼...
methods: {
scaleStart(event){
if (event.type != "touchstart") return false;
let currentPoint = {
x: event.touches[0].x,
y: event.touches[0].y
}
this.drawCircle(currentPoint);
this.setData({startPoint:currentPoint});
},
drawCircle(point){//這里負責點
let ctx = this.data.ctx;
ctx.beginPath();
ctx.fillStyle = this.data.lineColor;
//筆跡粗細由圓的大小決定
ctx.arc(point.x, point.y, this.data.radius, 0 , 2 * Math.PI);
ctx.fill();
ctx.closePath();
},
//省略以下代碼...
}
})Component({
//省略以上代碼
methods:{
drawLine(sourcePoint, targetPoint){
let ctx = this.data.ctx;
this.drawCircle(targetPoint);
ctx.beginPath();
ctx.strokeStyle = this.data.lineColor;
ctx.lineWidth = this.data.radius * 2;//這里乘2是因為線條的粗細要和圓的直徑相等
ctx.moveTo(sourcePoint.x, sourcePoint.y);
ctx.lineTo(targetPoint.x, targetPoint.y);
ctx.stroke();
ctx.closePath();
},
clearCanvas(){//清空畫布
let ctx = this.data.ctx;
ctx.rect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
ctx.fillStyle = "#FFFFFF";
ctx.fill();
}
}
})關于“微信小程序怎么實現簡單手寫簽名組件”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“微信小程序怎么實現簡單手寫簽名組件”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。