html
<template>
<view class="canvas">
<canvas canvas-id="myCanvas" :width="canvasWidth" :height="canvasHeight" :style="{height:canvasHeight+'px'}" @touchstart="onstart($event)" @touchmove="onmove($event)" @touchend="onend($event)"></canvas>
<button type="default" @click="clear">清除</button>
<button type="default" @click="Submit">提交</button>
<image :src="hcSrc" class="qianming" :style="{height:canvasHeight+'px'}"></image>
</view>
</template>
script
export default{
data(){
return{
canvasHeight:568,
canvasWidth:320,
ctx:null,
points:[],
hcSrc:'',
bgcImg:'/static/12.jpg',
}
},
onLoad() {
console.log('onLoad')
},
onReady() {
this.mapping();
},
created(){
console.log('oncreated')
},
mounted(){
console.log('munted')
let _this = this;
uni.getSystemInfo({
success(res) {
console.log(res)
_this.canvasHeight = res.screenHeight-100;
_this.canvasWidth = res.screenWidth;
}
})
},
methods:{
close:function(){
this.clear();
},
mapping(){
let _this = this;
const ctx = wx.createCanvasContext('myCanvas',this);
uni.getImageInfo({
src:_this.bgcImg,
success(res){
console.log(res)
ctx.drawImage(res.path, 0, 0, _this.canvasWidth, _this.canvasHeight);
ctx.draw(true);
}
})
this.ctx = ctx;
this.ctx.lineWidth = 4;
this.ctx.lineCap = "round";
this.ctx.lineJoin = "round";
},
onstart($event){
let startX = $event.changedTouches[0].x;
let startY = $event.changedTouches[0].y;
let startPoint = {X:startX,Y:startY};
this.points.push(startPoint);
this.ctx.beginPath();
},
onmove($event){
let moveX = $event.changedTouches[0].x;
let moveY = $event.changedTouches[0].y;
let movePoint = {X:moveX,Y:moveY};
this.points.push(movePoint);
let len = this.points.length;
if(len>=2){
this.draw();
}
},
onend($event){
this.points = [];
},
draw(){
let point1 = this.points[0];
let point2 = this.points[1];
this.points.shift();
this.ctx.moveTo(point1.X,point1.Y);
this.ctx.lineTo(point2.X,point2.Y);
this.ctx.stroke();
this.ctx.draw(true);
},
clear:function(){
let _this = this;
uni.getSystemInfo({
success(res) {
let canvasw = res.screenWidth;
let canvash = res.screenHeight-100;
_this.ctx.clearRect(0,0,canvasw,canvash);
_this.ctx.draw(true);
}
})
},
Submit(){
let _this = this;
uni.canvasToTempFilePath({
canvasId:'myCanvas',
success(res) {
console.log(res)
_this.hcSrc = res.tempFilePath;
}
})
},
}
}
css
uni-canvas,.qianming{
width: 100%;
height: 100%;
}
.canvas{
position: relative;
}
button{
width: 25%;
display: inline-block;
text-align: center;
}