目录
涂鸦
<canvas canvas-id='canvasId' class='myCanvas' bindtouchstart="touchStart" bindtouchmove="touchMove"></canvas>
1、获取画布的宽高
onLoad: function () {
// 获取画布的宽、高
wx.createSelectorQuery().select('.myCanvas').boundingClientRect().exec(res => {
this.setData({
canvasWidth: res[0].width,
canvasHeight: res[0].height
});
this.initCanvas();
})
}
2、初始化画布、画笔
initCanvas() {
this.ctx = wx.createCanvasContext('canvasId');
this.ctx.setStrokeStyle('#000');
this.ctx.setLineWidth(5);
this.ctx.setLineCap('round');
},
3、监听手势,开始绘制
touchStart(e) {
this.ctx.moveTo(e.touches[0].x,e.touches[0].y);
},
/**
* 监听手势滑动,绘制path
*/
touchMove(e) {
let tempX = e.touches[0].x;
let tempY = e.touches[0].y
this.ctx.lineTo(tempX,tempY);
this.ctx.stroke();
this.ctx.draw(true);
this.ctx.moveTo(tempX,tempY); // 绘制完成后,再将临时点作为起始点
},
/**
* 清空
*/
reset(){
this.ctx.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
this.ctx.draw();
},
/**
* 加粗
*/
bold(){
this.ctx.setLineWidth(10);
},
/**
* 换色
*/
color(){
this.ctx.setStrokeStyle('#f00');
},
绘制文本
this.ctx.font = 'normal 30px sans-serif';
this.ctx.fillStyle = '#f00';
let text = '镜花水月';
// y坐标从文字左下角开始算,measureText仅支持获取文本的宽度
this.ctx.fillText(text, 0, this.ctx.measureText('镜').width);
this.ctx.draw();
绘制图片
this.ctx.drawImage('本地路径', 0, 0, '绘制宽度', '绘制高度');
this.ctx.draw();