用Canvas自己写个小画板
2021-12-22 本文已影响0人
又菜又爱分享的小肖
- 首先写好
触摸开始
,触摸移动
,结束触摸事件
<canvas disable-scroll="true" canvas-id="drawline" class="board" @touchstart="handtouchstart" @touchmove="handtouchmove"
@touchend="handtouchend">
</canvas>
- 定义全局接收变量
data() {
return {
x: 0, // 渠道开始和移动位置
y: 0,
newx: 0,
newy: 0
}
},
- 创建 canvas 绘图上下文
var ctx = uni.createCanvasContext('drawline')
- 获取到用户的手势点击
x
,y
轴位置
// 触摸开始
handtouchstart(e) {
let startX = e.changedTouches[0].x;
let startY = e.changedTouches[0].y;
this.x = startX;
this.y = startY;
},
- 获取用户的触摸移动位置, 并根据位置进行绘制
// 触摸移动
handtouchmove(e) {
let moveX = e.changedTouches[0].x;
let moveY = e.changedTouches[0].y;
this.newx = moveX;
this.newy = moveY;
ctx.setLineWidth(10); // 划线多粗
ctx.setLineCap('round'); // 不中断
ctx.setStrokeStyle('red')
ctx.moveTo(this.x, this.y)
ctx.lineTo(this.newx, this.newy)
ctx.stroke()
ctx.draw(true) // 保存绘画内容
this.x = moveX
this.y = moveY
this.main(this.x, this.y);
},
- 结束触摸 可清空原本绘制的图像 也可不
// 结束触摸
handtouchend(e) {
ctx.draw() // 清空
},