以下代码在仅在基础库2.6版本无法正常运行,其他版本暂未测出问
1.横版JSON配置
2.效果预览
3.代码实现
3.1 HTML
<view class="container">
<canvas
type="2d"
id="myCanvas"
style="width:100vw;height:90vh;border-bottom:1px solid grey"
capture-bind:touchstart="touchStart"
capture-bind:touchmove="touchMove"
>
</canvas>
<view class="optionBtn">
<view class="btnStyle">
<view class="rotateText" bindtap="reset">重置</view>
</view>
<view class="line"></view>
<view class="btnStyle">
<view class="rotateText" bindtap="sure">确定</view>
</view>
</view>
</view>
3.2 CSS
.container{
width: 100vw;
height: 100vh;
}
.optionBtn{
width: 100vw;
height:10vh;
display: flex;
align-items: center;
justify-content: center;
}
.line{
width: 1rpx;
height: 10vh;
background: black;
}
.btnStyle{
width:50vw;
height:10vh;
display: flex;
align-items: center;
justify-content: center;
}
3.3 JSON
{
"usingComponents": {},
"pageOrientation": "landscape",
"disableScroll": true
}
3.4 JS
Page({
data:{
signPath:[]
},
//初始化画布
init(data){
const width = data[0].width;
const height=data[0].height;
const canvas = data[0].node;
const ctx = canvas.getContext('2d');
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = width * dpr
canvas.height = height * dpr
ctx.scale(dpr,dpr)
this._dpr = dpr
this._ctx = ctx
this._canvas = canvas
},
//获取初始点位置
touchStart(e){
console.log(e)
const { _ctx:ctx } = this
const { clientX:x ,clientY:y } = e.touches[0]
ctx.beginPath()
},
//绘制路径
touchMove(e){
const { _ctx:ctx } = this
const { clientX:x ,clientY:y } = e.touches[0]
this.data.signPath.push([x,y])
this.setData({
signPath:this.data.signPath
})
ctx.lineTo(x, y)
ctx.stroke()
},
//重绘
reset(){
const { _ctx:ctx,_canvas:canvas } = this
//初始化绘制路径
this.setData({
signPath:[]
})
ctx.clearRect(10, 10, canvas.width, canvas.height)
},
//提交签名图片
sure(){
if(this.data.signPath.length <= 0){
wx.showToast({
title: '签名不能为空',
icon:'none'
})
return
}
//导出图片
this.outImage()
},
//导出图片
outImage(){
const { _canvas:canvas,_dpr:dpr } = this
wx.canvasToTempFilePath({
x: 0,
y: 0,
width:canvas.width / dpr,
height:canvas.height / dpr,
destWidth:canvas.width,
destHeight:canvas.height,
canvas:canvas,
success(res) {
console.log(res.tempFilePath)
},
complete(e){
console.log(e)
}
},this)
},
onLoad(){
wx.createSelectorQuery()
.select('#myCanvas')
.fields({node: true,size: true})
.exec(this.init.bind(this))
}
})