使用uniapp实现canvas画布实现手写签名效果的示例代码,要可以保存签名和清空
时间: 2024-01-06 07:04:10 浏览: 115
以下是一个简单的示例代码,实现了使用uniapp的canvas组件实现手写签名效果,并提供了保存和清空的功能。
template:
```html
<template>
<view>
<canvas canvas-id="myCanvas" style="width:100%;height:400rpx;background-color: #fff;" bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd"></canvas>
<view class="btn-group">
<button type="primary" class="btn" @tap="save">保存</button>
<button type="default" class="btn" @tap="clear">清空</button>
</view>
</view>
</template>
```
script:
```javascript
<script>
export default {
data() {
return {
ctx: null, // canvas绘图上下文
lastX: 0, // 上一次触摸的X坐标
lastY: 0, // 上一次触摸的Y坐标
isDrawing: false // 是否正在绘制
}
},
mounted() {
// 获取canvas绘图上下文
this.ctx = uni.createCanvasContext('myCanvas', this);
},
methods: {
touchStart(e) {
// 记录起始点坐标
this.lastX = e.changedTouches[0].x;
this.lastY = e.changedTouches[0].y;
// 开始绘制
this.isDrawing = true;
},
touchMove(e) {
if (this.isDrawing) {
// 获取当前坐标
const currentX = e.changedTouches[0].x;
const currentY = e.changedTouches[0].y;
// 绘制线条
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(currentX, currentY);
this.ctx.stroke();
// 更新上一次坐标
this.lastX = currentX;
this.lastY = currentY;
}
},
touchEnd() {
// 结束绘制
this.isDrawing = false;
},
save() {
// 保存签名
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
success: (res) => {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功'
})
}
})
}
}, this);
},
clear() {
// 清空画布
this.ctx.clearRect(0, 0, uni.upx2px(750), uni.upx2px(400));
this.ctx.draw();
}
}
}
</script>
```
需要注意的是,canvas组件的宽度和高度应该使用rpx或者upx作为单位,并且在保存签名时,需要先使用canvasToTempFilePath方法将canvas转换成临时文件路径,再使用saveImageToPhotosAlbum方法保存到相册中。
阅读全文
相关推荐
















