wxml
<view class="signName">
<view class="btnList">
<van-button size="small" bindtap="clearCanvas">清空</van-button>
</view>
<view class="handCenter">
<canvas class="canvas" disable-scroll="{{true}}" id="myCanvas" bindtouchstart="scaleStart" bindtouchmove="scaleMove" bindtouchend="scaleEnd" bindtap="mouseDown" type="2d">
</canvas>
</view>
</view>
<button bindtap="xiaZai">下载</button>
wxss
.signName{
width: 100vw;
height: 70vh;
}
.handCenter{
height: 800rpx;
}
.canvas{
width: 100%;
height: 100%;
background-color: burlywood;
}
js
Page({
data: {
canvas: {}
},
onShow() {
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
this.width = canvas.width;
this.height = canvas.height;
ctx.scale(dpr, dpr)
this.ctx = ctx;
this.setData({
canvas: canvas
})
})
},
scaleStart(e) {
let {
x,
y
} = e.touches[0]
console.log(x, y)
this.ctx.beginPath()
this.ctx.moveTo(x, y)
this.ctx.strokeStyle = "#000";
this.ctx.lineWidth = '5'
},
scaleMove(e) {
let {
x,
y
} = e.touches[0]
this.ctx.lineTo(x, y)
this.ctx.stroke();
this.ctx.lineCap = "round";
this.ctx.moveTo(x, y)
},
scaleEnd(e) {
console.log(111, e)
this.ctx.lineCap = "round";
},
xiaZai() {
wx.canvasToTempFilePath({
canvas: this.data.canvas, // canvas 实例
success(res) {
console.log(res);
// canvas 生成图片成功
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
// 保存成功
wx.showToast({
title: '已保存相册',
icon: 'success',
duration: 2000
})
}
})
}
})
},
clearCanvas() {
this.ctx.clearRect(0, 0, this.width, this.height)
this.ctx.draw(true)
}
})