效果图:
wxml:
<view class="root">
<canvas
id="myCanvas" class="myCanvas" type="2d"
bindtouchstart="startTouchClick"
bindtouchmove="moveClick"
bindtouchend="endTouchClick"
binderror="errorClick"></canvas>
<view class="btnBox">
<view class="palin" bindtap="initCanvas">重新签字</view>
<view class="submint">确认提交</view>
</view>
</view>
js:
Page({
/**
* 页面的初始数据
*/
data: {
ctx : '',
},
startTouchClick(e){
console.log("开始触碰事件:",e);
let ctx = this.data.ctx;
ctx.beginPath();//起始一条路径,或重置当前路径
ctx.moveTo(e.changedTouches[0].x, e.changedTouches[0].y) // 把路径移动到画布中的指定点,不创建线条。用 stroke 方法来画线条
},
moveClick(e){
console.log("移动事件:",e);
let ctx = this.data.ctx;
ctx.lineTo(e.changedTouches[0].x, e.changedTouches[0].y) // 增加一个新点,然后创建一条从上次指定点到目标点的线。
ctx.lineWidth=2.5;//设置轨迹的宽度
ctx.stroke()//用 stroke 方法来画线条
},
//触摸结束
endTouchClick(e){
console.log("触碰结束事件:",e);
},
//误触事件
errorClick(e){
console.log("误触事件:",e);
},
//初始化画布
initCanvas(){
let ctx ;
wx.createSelectorQuery()
.select('#myCanvas') // 在 WXML 中填入的 id
.fields({ node: true, size: true })
.exec((res) => {
// Canvas 对象
const canvas = res[0].node
this.setData({
canvas : canvas
})
// 渲染上下文
ctx = canvas.getContext('2d')
this.setData({
ctx : ctx
})
// Canvas 画布的实际绘制宽高
const width = res[0].width
const height = res[0].height
// 初始化画布大小
const dpr = wx.getWindowInfo().pixelRatio
this.setData({
dpr : dpr
})
canvas.width = width * dpr
canvas.height = height * dpr//设置宽高
ctx.scale(dpr, dpr)//scale() : 缩放当前绘图至更大或更小
// 清空画布
ctx.clearRect(0, 0, width, height)
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
this.initCanvas();
},
onReady(){
},
})
wxss:
.root {
width: 98%;
margin: 2% 0 3% 2% ;
height: 90vh;
display: flex;
align-items: center;
}
.myCanvas {
width: 80%;
height: 100%;
background-color: white;
border: 1px dashed #4E85F6;
}
.btnBox{
width: 20%;
margin-top: 50vh;
}
.palin{
border: 2px solid #4E85F6;
margin: 0 10% 20%;
text-align: center;
color: #4E85F6;
background-color: #ffffff;
height: 40px;
line-height: 40px;
border-radius: 40px;
font-size: 14px;
}
.submint{
margin: 0 10% 20%;
text-align: center;
height: 40px;
line-height: 40px;
border-radius: 40px;
font-size: 14px;
background-color: #4E85F6;
border: 2px solid #4E85F6;
color: #ffffff;
}
json:
{
"navigationBarTitleText": "收货签字",
"pageOrientation":"landscape",
"usingComponents": {}
}