View:
<template>
<view class="container">
<view class="canvas-container">
<canvas class="mycanvas" canvas-id="mycanvas"></canvas>
<image :src="imageSrc" mode="aspectFit" @load="onLoad"></image>
</view>
<view class="button-container">
<button type="primary" @click="clearCanvas">清除</button>
<button type="primary" @click="saveImage">保存</button>
</view>
</view>
</template>
JS:
<script>
export default {
data: {
imageSrc: "",
canvasWidth: 0,
canvasHeight: 0,
ctx: null,
drawing: false,
lastX: 0,
lastY: 0,
lineWidth: 1
},
onReady() {
wx.getSystemInfo({
success: res => {
this.canvasWidth = res.windowWidth;
this.canvasHeight = (res.windowHeight - 100) * 0.75;
const ctx = wx.createCanvasContext("mycanvas", this);
this.ctx = ctx;
ctx.setFillStyle("#000000");
ctx.setLineWidth(this.lineWidth);
ctx.stroke();
}
});
},
methods: {
onLoad(event) {
const { width, height } = event.detail;
this.imageSrc = event.currentTarget.src;
if (width / height > this.canvasWidth / this.canvasHeight) {
this.canvasHeight = this.canvasWidth * (height / width);
} else {
this.canvasWidth = this.canvasHeight * (width / height);
}
this.ctx.drawImage(this.imageSrc, 0, 0, this.canvasWidth, this.canvasHeight);
this.ctx.stroke();
},
handleTouchStart(event) {
this.drawing = true;
this.lastX = event.touches[0].x - $event.currentTarget.offsetLeft;
this.lastY = event.touches[0].y - $event.currentTarget.offsetTop;
},
handleTouchEnd() {
this.drawing = false;
},
handleTouchMove(event) {
if (this.drawing) {
const currentX = event.touches[0].x - $event.currentTarget.offsetLeft;
const currentY = event.touches[0].y - $event.currentTarget.offsetTop;
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(currentX, currentY);
this.ctx.closePath();
this.ctx.stroke();
this.lastX = currentX;
this.lastY = currentY;
}
},
clearCanvas() {
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.ctx.drawImage(this.imageSrc, 0, 0, this.canvasWidth, this.canvasHeight);
this.ctx.stroke();
},
saveImage() {
wx.canvasToTempFilePath({
canvasId: "mycanvas",
success: res => {
wx.getFileSystemManager().readFile({
filePath: res.tempFilePath,
encoding: "base64",
success: data => {
console.log("data:image/png;base64," + data.data);
}
});
}
}, this);
},
handleLineWidthChange(value) {
this.lineWidth = value;
this.ctx.setLineWidth(value);
},
}
};
</script>
Style:
<style lang="scss">
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
}
.canvas-container {
position: relative;
margin-bottom: 20px;
}
.mycanvas {
position: absolute;
left: 0;
top: 0;
}
.button-container {
display: flex;
justify-content: center;
}
</style>