canvas.wxml
<view class="container">
<view class="canvas_area">
<canvas
canvas-id="myCanvas"
class="myCanvas"
disable-scroll="{{false}}"
bindtouchstart="touchStart"
bindtouchmove="touchMove"
bindtouchend="touchEnd"
></canvas>
</view>
<view class="canvas_tools">
<view class="box box1" bindtap="penSelect" data-param="5">细</view>
<view class="box box2" bindtap="penSelect" data-param="15">粗</view>
<view class="box box3" bindtap="colorSelect" data-param="#cc0033"></view>
<view class="box box4" bindtap="colorSelect" data-param="#ff9900"></view>
<view class="box box5" bindtap="handleOperate">操作</view>
</view>
</view>
canvas.wxss
page{
height: 100%;
}
.container {
width: 100%;
height: 100%;
position: relative;
}
.canvas_area {
width: 100%;
height: 100%;
background-color: lightblue;
}
.myCanvas {
width: 100%;
height: 100%;
}
.canvas_tools {
position: absolute;
left: 0;
bottom: 20rpx;
width: 100%;
height: 100rpx;
display: flex;
flex-direction: row;
justify-content: space-around;
}
.box {
width: 100rpx;
height: 100rpx;
background-color: rebeccapurple;
border-radius: 50%;
}
.box1, .box2, .box5 {
color: #fff;
text-align: center;
line-height: 100rpx;
}
.box3 {
background-color: #cc0033;
}
.box4 {
background-color: #ff9900;
}
canvas.js
Page({
startX: 0,
startY: 0,
data: {
pen: 2,
color: "#00ff00",
},
penSelect(e) {
this.setData({
pen: parseInt(e.currentTarget.dataset.param)
});
this.clearCanvas();
},
colorSelect (e) {
this.setData({
color: e.currentTarget.dataset.param
});
},
clearCanvas() {
console.log("............");
this.context.draw();
},
touchStart(e) {
this.startX = e.changedTouches[0].x;
this.startY = e.changedTouches[0].y;
this.context = wx.createCanvasContext('myCanvas', this);
this.context.setStrokeStyle(this.data.color);
this.context.setLineWidth(this.data.pen);
this.context.setLineCap("round");
this.context.beginPath();
},
touchMove(e) {
let startX1 = e.changedTouches[0].x;
let startY1 = e.changedTouches[0].y;
this.context.moveTo(this.startX, this.startY);
this.context.lineTo(startX1, startY1);
this.context.stroke();
this.startX = startX1;
this.startY = startY1;
wx.drawCanvas({
canvasId: "myCanvas",
reserve: true,
actions: this.context.getActions()
});
},
touchEnd() {
},
handleOperate() {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
quality: 0,
success: (res) => {
console.log(res);
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
wx.showToast({
title: '保存成功'
})
},
fail: (err) => {
if (err.errMsg) {
wx.showModal({
title: '提示',
content: '您好,请先授权,在保存此图片!',
showCancel: false,
success(res) {
if (res.confirm) {
wx.openSetting({
complete: (settingdata) => {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
wx.showToast({
title: '授权成功'
})
} else {
wx.showToast({
title: '授权失败'
})
}
},
})
}
}
})
}
}
});
}
})
}
})
效果图