uniapp中使用canvas
以下是一个移动端人员签到例子:
view
<view class="signName"> <canvas class="signCanvas" canvas-id="canvasId" @touchstart="touchstart" @touchmove.stop.prevent="touchmove" id="canvasId"></canvas>
</view> <view class="btnBox"> <view class="cancel" @click="clear()">清除</view> <view class="submit" @click="sure()">提交</view> </view>
data声明变量
data() { return { context: '', moveX: '', moveY: '', } },
mounted
mounted() { // 创建绘图对象 let context = uni.createCanvasContext('canvasId') // 设置线条 context.lineWidth = 4 context.setLineCap('round') context.setLineJoin('round') // 赋值 this.context = context },
methods
methods: { touchstart(e) { // 取出x、y的值 let { x, y } = e.changedTouches[0] // 绘制线条起点 this.context.beginPath() this.context.moveTo(x, y) // 起点与移动的连接断开 this.moveX = '' this.moveY = '' }, touchmove(e) { // 取出x, y的值 let { x, y } = e.changedTouches[0] // 防止线条出现断点 if (this.moveX && this.moveY) { this.context.moveTo(this.moveX, this.moveY) this.context.lineTo(this.moveX, this.moveY) } this.context.lineTo(x, y) this.moveX = x this.moveY = y this.context.stroke() // ture,保留之前的内容 this.context.draw(true) }, // 清除 clear() { this.context.draw() this.moveX = '' this.moveY = '' }, sure() { this.signImage() this.$emit('close','') }, // 导出图片 signImage() { uni.showLoading({ title: '签到中...', mask: true }); let { windowWidth, windowHeight } = this uni.canvasToTempFilePath({ x: 0, y: 0, canvasId: 'canvasId', fileType: 'jpg', success: (res) => { // 在H5平台下,tempFilePath 为 base64 this.pathToBase64App(res.tempFilePath) // this.uploadFile(res.tempFilePath) }, fail: (res) => { console.log(res) } }) }, pathToBase64App(path) { let that = this; // 通过URL参数获取目录对象或文件对象 plus.io.resolveLocalFileSystemURL(path, function(entry) { entry.file(function(file) { let fileReader = new plus.io.FileReader() fileReader.onload = function(evt) { let base64 = evt.target.result.split(',')[1] that.uploadSign(base64) } fileReader.onerror = function(error) { console.log('failed: ', error); } fileReader.readAsDataURL(file) }, function(error) { console.log('failed: ', error); }) }, function(error) { console.log('failed: ', error); }) }, uploadSign(base64) { uploadSign({ fileBase64: base64, meetingId: this.meetInfo.MeetingId, uploadId: this.meetInfo.PersonnelId, uploadName: this.meetInfo.PersonnelName, fileName: this.meetInfo.PersonnelName + '签到' }).then(res => { uni.hideLoading() this.$emit('close','') this.getMeeting(); uni.showToast({ title: '签到成功', icon: 'none', duration: 2000 }) }) }, getMeeting() { getMeeting({ Mac: this.macId?this.macId:'4' }).then(res => { if (res.success) { this.$store.commit('setMeetInfo', res.result) } }) }, }
注: getMeeting( ) uploadSign( )这两个方法是接口,依据实际情况而定。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通