微信小程序 canvas 字體自動換行(支持換行符)


微信小程序 canvas 自動適配 自動換行,保存圖片分享到朋友圈  https://github.com/richard1015/News

微信IDE演示代碼https://developers.weixin.qq.com/s/WCkpsTm97M7p

function findBreakPoint(text, width, context) {
  var min = 0;
  var max = text.length - 1;
  while (min <= max) {
    var middle = Math.floor((min + max) / 2);
    var middleWidth = context.measureText(text.substr(0, middle)).width;
    var oneCharWiderThanMiddleWidth = context.measureText(text.substr(0, middle + 1)).width;
    if (middleWidth <= width && oneCharWiderThanMiddleWidth > width) {
      return middle;
    }
    if (middleWidth < width) {
      min = middle + 1;
    } else {
      max = middle - 1;
    }
  }

  return -1;
}
function breakLinesForCanvas(context, text, width, font) {
  var result = [];
  if (font) {
    context.font = font;
  }
  var textArray = text.split('\r\n');
  for (let i = 0; i < textArray.length; i++) {
    let item = textArray[i];
    var breakPoint = 0;
    while ((breakPoint = findBreakPoint(item, width, context)) !== -1) {
      result.push(item.substr(0, breakPoint));
      item = item.substr(breakPoint);
    }
    if (item) {
      result.push(item);
    }
  }
  return result;
}
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    id: 0,
    info: {}
  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#010101',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    console.log(options)
    let id = options.id;
        let info ={
            "title":"asdasd啊啊啊asdasd啊啊啊asdasd啊啊啊asdasd啊啊啊asdasd啊啊啊",
            "intro":"我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容我是內容"
        };
        self.setData({
          info
        });
        self.drawInit(info);
  },
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
  /**
  * 生命周期函數--監聽頁面初次渲染完成
  */
  onReady: function (e) { },
  /**
   * 繪制圖片
   */
  drawInit: function (info) {
    var contentTitle = info.title;
    var contentStr = info.intro;
    var that = this
    var res = wx.getSystemInfoSync();
    var canvasWidth = res.windowWidth;
    // 獲取canvas的的寬  自適應寬(設備寬/750) px
    var Rpx = (canvasWidth / 375).toFixed(2);
    //畫布高度 -底部按鈕高度
    var canvasHeight = res.windowHeight - Rpx * 59;
    // 使用 wx.createContext 獲取繪圖上下文 context
    var context = wx.createCanvasContext('secondCanvas')
    //設置行高
    var lineHeight = Rpx * 30;
    //左邊距
    var paddingLeft = Rpx * 20;
    //右邊距
    var paddingRight = Rpx * 20;
    //當前行高
    var currentLineHeight = Rpx * 20;
    //背景顏色默認填充
    context.fillStyle = "#f8f8f8";
    context.fillRect(0, 0, canvasWidth + Rpx * 2, canvasHeight);
    //標題內容顏色默認
    context.fillStyle = "#fff";
    //高度減去 圖片高度
    context.fillRect(Rpx * 15, Rpx * 15, canvasWidth - Rpx * 30, canvasHeight);
    //設置標題
    var resultTitle = breakLinesForCanvas(context, contentTitle, canvasWidth - paddingLeft - paddingRight, `${(Rpx * 20).toFixed(0)}px PingFangSC-Regular`);
    //字體顏色
    context.fillStyle = '#000000';
    resultTitle.forEach(function (line, index) {
      currentLineHeight += Rpx * 30;
      context.fillText(line, paddingLeft, currentLineHeight);
    });
    //畫分割線
    currentLineHeight += Rpx * 15;
    context.setLineDash([Rpx * 6, Rpx * 3.75]);
    context.moveTo(paddingLeft, currentLineHeight);
    context.lineTo(canvasWidth - paddingRight, currentLineHeight);
    context.strokeStyle = '#cccccc';
    context.stroke();
    //設置內容
    var result = breakLinesForCanvas(context, contentStr || '無內容', canvasWidth - paddingLeft - paddingRight, `${(Rpx * 16).toFixed(0)}px PingFangSC-Regular`);
    console.log(result);
    //字體顏色
    context.fillStyle = '#666666';
    result.forEach(function (line, index) {
      currentLineHeight += Rpx * 30;
      context.fillText(line, paddingLeft, currentLineHeight);
     }
    context.draw();
  },
  saveImg: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'secondCanvas',
      fileType: 'jpg',
      success: function (res) {
        console.log(res.tempFilePath)  // 返回圖片路徑
        wx.showLoading({
          title: '保存中...',
          mask: true
        });
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            })
          }, fail: function (res) {
            wx.hideLoading()
            console.log(res)
          }
        })
      }
    })
  }
})
         


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM