1. HTML
<canvas canvas-id="jushiSignature" width="300" height="300"
disable-scroll="true" @touchstart="touchstart"
@touchmove="touchmove" @touchend="touchend">
</canvas>
2. JS
//准备好路径点
data(){
return{
points:[] //路径点
tempPoint:[] //存放当前画纸上的轨迹点
}
}
//首先获取canvas上下文,在created里面获取并设置好画笔样式
created(){
ctx=uni.createCanvasContext('jushiSignature',this)
ctx.lineWidth=750 //线条的宽度
ctx.lineCap="round" //线条的端点样式
ctx.lineJoin="round" //线条的交点样式
ctx.setStrokeStyle('red') //设置边框颜色
}
//开始绘制
touchstart(e){
const startX=e.changedTouches[0].x //用户按下屏幕的坐标 x
const startY=e.changedTouches[0].y //用户按下屏幕的坐标 y
let startPoint={
X:startX,
Y:startY
}
this.points.push(startPoint) //添加路径点
ctx.beginPath() //开始创建一个路径
}
//记录下移动式的点位
touchmove(e){
let moveX=e.changedTouches[0].x
let moveY=e.changedTouches[0].y
let movePoint={
X:moveX,
Y:moveY
}
this.points.push(movePoint) //存点
if(this.points.length>=2){
this.draw()//绘制路径
}
this.tempPoint.push(movePoint)
}
//清空未绘制的点避免对后续路径产生干扰
touchend(){
this.points=[]
}
//绘制笔迹
//1. 移动的同时绘制笔迹,保证实时显示
//2. 从路径中取两个点作为起点(moveTo)和终点(lineTo)保证笔迹连续性
//3. 把上一次的终点作为下一次的起点(清除第一个点)
draw(){
let p1=points[0]
let p2=points[1]
this.points.shift()//清除第一个点
ctx.moveTo(p1.X,p1.Y) //把路径移动到画布中的指定点,不创建线条
ctx.lineTo(p2.x,p2.Y) //增加一个新点,然后创建一条从上次指定点到目标点的线
ctx.stroke() //画出当前路径的边框
ctx.draw(true) //将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中,true表示保存当前画布的内容,本次调用drawCanvas绘制的内容覆盖在上面
}
//保存绘制的内容为图片,并返回文件路径。需要使用uni.canvasToTempFilePath()
uni.canvasToTempFilePath({
canvasId:'jushiSignature',
fileType:'jpg', //目标文件的类型
quality:1, //图片的质量
success:function(res){
console.log(res.tempFilePath) //res.tempFilePath就是图片的路径
}
})
//清空画布
clear(){
uni.getSystemInfo({ //这里主要用来获取可使用窗口宽度和高度
success:function(res){
ctx.clearRect(0,0,res.windowWidth,res.windowHeight) //清除画布上在该矩形区域内的内容
ctx.draw(true)
//重新绘制画笔样式
ctx.lineWidth=750 //线条的宽度
ctx.lineCap="round" //线条的端点样式
ctx.lineJoin="round" //线条的交点样式
ctx.setStrokeStyle('red') //设置边框颜色
}
})
}