微信小程序Canvas绘制轨迹 隐藏 不影响canvas绘图处理办法

1,173 阅读1分钟

最近在写小程序轨迹还原,使用的是小程序的canvas,碰到一个问题,就是canvas层隐藏之后,在现实不能绘图 后面发现在开发工具里面不能显示,但是真机却能显示 下面贴出canvas画推荐的代码

// 画布相关
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;//是否在绘制中
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度
var lastPointX = undefined;
var lastPointY = undefined;
//画布初始化执行
  startCanvas: function () {
    var that = this;
    //创建canvas
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineCap('round');
    context.setLineJoin('round');

    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        canvasw = res.windowWidth - 0;//设备宽度
        canvash = canvasw * 7920 / 5600;
        that.setData({ 'canvasw': canvasw });
        that.setData({ 'canvash': canvash });
      }
    });
  },
  // 写画布
  draw: function ( x, y  ) {
    var force = 144;
    // console.log(`坐标:(${x},${y}); 力度:${force}`);
    const lineWidth = (1 + 0.5 * force / 100.0) * 50.0 / 100.0;
    context.setLineWidth(lineWidth);
    const pointX = x * canvasw / 5600;
    const pointY = y * canvash / 7920;

    if (lastPointX === undefined && lastPointY === undefined) {
      context.moveTo(pointX, pointY);
    } else {
      context.moveTo(lastPointX, lastPointY);
      context.lineTo(pointX, pointY);
    }
    lastPointX = pointX;
    lastPointY = pointY;

    context.stroke();
    context.draw(true);
    this.lastPointX = pointX;
    this.lastPointY = pointY;
  },