生成一段代码用来展示canvas.toDataURL()方法在uni-app里的使用
时间: 2024-05-15 22:19:02 浏览: 188
当然,以下是使用canvas.toDataURL()方法在uni-app里的示例代码:
```javascript
<template>
<canvas class="canvas" @touchstart="startDrawing" @touchmove="drawing" @touchend="endDrawing"></canvas>
</template>
<script>
export default {
data() {
return {
ctx: null,
isDrawing: false,
lastX: 0,
lastY: 0
}
},
mounted() {
this.ctx = uni.createCanvasContext('canvas', this.$mp.page)
},
methods: {
startDrawing(e) {
this.isDrawing = true
this.lastX = e.touches[0].x
this.lastY = e.touches[0].y
},
drawing(e) {
if (!this.isDrawing) return
this.ctx.beginPath()
this.ctx.moveTo(this.lastX, this.lastY)
this.ctx.lineTo(e.touches[0].x, e.touches[0].y)
this.ctx.stroke()
this.lastX = e.touches[0].x
this.lastY = e.touches[0].y
},
endDrawing() {
this.isDrawing = false
uni.showLoading({
title: '正在保存',
mask: true
})
uni.canvasToTempFilePath({
canvasId: 'canvas',
success: (res) => {
uni.hideLoading()
uni.previewImage({
current: res.tempFilePath,
urls: [res.tempFilePath]
})
},
fail: (res) => {
uni.hideLoading()
uni.showToast({
title: '保存失败,请重新保存',
icon: 'none'
})
}
}, this.$mp.page)
}
}
}
</script>
```
此示例展示了在Uni-app中使用 HTML5 Canvas API 绘制画布,并将画布内容转换为其 base64 编码的 DataURL,最后使用uni.previewImage()预览图像。
阅读全文
相关推荐

















