微信小程序-画板工具实现

2,704 阅读1分钟

画布html:

<canvas style="width: 100vw; height:81vh;border-top:.2vh solid #ddd;" canvas-id="palette" bindtouchstart='touchstart' bindtouchmove='touchMove' bindtouchend='touchEnd' disable-scroll='true'></canvas>

绘画实现:

 touchstart: function() {
    let tinct, lineWidth;
    if (this.data.brushState == 'p') {
      tinct = this.data.tinctList[this.data.tinctCurr];
      lineWidth = this.data.tinctSize;
    } else {
      tinct = "#ffffff";
      lineWidth = 20;
      this.context.setLineCap('round') ;//设置线条端点的样式
      this.context.setLineJoin('round') ;//设置两线相交处的样式
    }

    this.context.setStrokeStyle(tinct); //设置描边颜色
    this.context.setLineWidth(lineWidth); //设置线条宽度
    this.data.points.push({
      point: [],
      tinct: tinct,
      lineWidth: lineWidth
    });
  },
  touchMove: function(e) {
    let pos = e.touches[0],
      da = this.data,
      po = da.points[da.points.length - 1].point;
    po.push({
      x: pos.x,
      y: pos.y
    });
    this.bindDraw(po);
  },
  touchEnd: function(e) {
    console.log(this.data.points);
  },
  //绘制
  bindDraw: function(point) {
    this.context.moveTo(point[0].x, point[0].y);
    for (var i = 1; i < point.length; i++) {
      this.context.lineTo(point[i].x, point[i].y);
    }
    this.context.stroke();
    this.context.draw(true);
  },

切换成画笔/橡皮檫:

 <image class="{{brushState=='p'?'selected':''}}" src='/image/jd_pencil.png' data-state='p' bindtap='switchBrush'></image>
 <image class="{{brushState=='c'?'selected':''}}" src='/image/jd_eraser.png' data-state='c' bindtap='switchBrush'></image>
  switchBrush: function(e) {
    this.setData({
      brushState: e.currentTarget.dataset.state
    });
  },

绘制回退:

  <image src='/image/jd_back.png' bindtap='drawBack'></image>
  drawBack: function() {
    if (this.data.points.length == 0) return false;
    this.context.clearRect(0, 0, 400, 500);
    this.context.draw();
    this.data.points.pop();
    console.log(this.data.points);
    let po = this.data.points;
    for (let i = 0; i < po.length; i++) {
      this.context.setStrokeStyle(po[i].tinct); //设置描边颜色
      this.context.setLineWidth(po[i].lineWidth); //设置线条宽度
      // this.context.beginPath();
      this.bindDraw(po[i].point);
    }
  },

清空画布:

 <image src='/image/jd_clear.png' bindtap='drawClear'></image>
  drawClear:function(){
    this.context.clearRect(0, 0, 400, 500);
    this.context.draw();
    this.setData({points:[]});
    console.log(this.data.points);
  },

源码

萌生写画板小程序的想法,是因为之前画画练习下了绘画APP,又刚好学到小程序API的画布内容。两相结合,修修改改,形成了现在的功能。想法转变成实物,总是开心的 o((^▽^))o