天天看點

微信小程式:畫弧線,畫圓,繪制藝術字

1、首先在wxml裡建一個canvas

<canvas
  type="2d"
  id="canvas"
  style="width: 223rpx; height: 94rpx; display: block; box-sizing: border-box; left: 0rpx; top: 0rpx"
></canvas>
      

  

2、在js裡添加方法

//畫弧線
  drawCurve() {
    // 通過 SelectorQuery 擷取 Canvas 節點
    wx.createSelectorQuery().select('#canvas').node(function (res) {
      console.log(res.node) // 節點對應的 Canvas 執行個體。
      const canvas = res.node
      const ctx = canvas.getContext('2d')

      ctx.lineWidth=10
      ctx.strokeStyle = 'red'
      ctx.lineCap='round'
      ctx.beginPath()
      //arc(圓心x軸,圓心y軸,半徑機關像素,起始角度弧度制從x軸正方向開始,結束角度弧度制,true表示逆時針繪制)
      ctx.arc(canvas.width / 2, canvas.height-ctx.lineWidth,canvas.height-(ctx.lineWidth*2), 0, 3.14926,true)
      ctx.stroke()

    }).exec()
  },
//畫圓
drawCircle() {
  // 通過 SelectorQuery 擷取 Canvas 節點
  wx.createSelectorQuery().select('#canvas').node(function (res) {
    console.log(res.node) // 節點對應的 Canvas 執行個體。
    const canvas = res.node
    const ctx = canvas.getContext('2d')

    ctx.strokeStyle = 'red'
    ctx.beginPath()
    //arc(圓心x軸,圓心y軸,半徑機關像素,起始角度弧度制從x軸正方向開始,結束角度弧度制,true表示逆時針繪制)
    ctx.arc(canvas.width / 2, canvas.height / 2,50, 0, 2*3.14926,true)
    ctx.stroke()

  }).exec()
}
      

效果

微信小程式:畫弧線,畫圓,繪制藝術字

繪制藝術字:

//繪制文字
  drawText() {
    // 通過 SelectorQuery 擷取 Canvas 節點
    wx.createSelectorQuery().select('#canvas').node(function (res) {
      console.log(res.node) // 節點對應的 Canvas 執行個體。
      const canvas = res.node
      const ctx = canvas.getContext('2d')

      ctx.font = "50px sans-serif"
      //ctx.fillText("Hello World", 10, 100);
      ctx.strokeText("Hello World", 10, 100)

    }).exec()
  },
      

效果:

微信小程式:畫弧線,畫圓,繪制藝術字

 删除指定文字

//繪制文字删除線
    drawTextDelete() {
      // 通過 SelectorQuery 擷取 Canvas 節點
      wx.createSelectorQuery().select('#canvas').node(function (res) {
        console.log(res.node) // 節點對應的 Canvas 執行個體。
        const canvas = res.node
        const ctx = canvas.getContext('2d')
  
        ctx.font = "50px sans-serif"
        ctx.fillText("Hello World", 10, 100);
  
        //ctx.globalCompositeOperation = "source-over"; //全局合成操作
        ctx.fillStyle = "red";
        ctx.fillRect(15, 80, 85, 10);

        //ctx.globalCompositeOperation = "source-over"; //全局合成操作
        ctx.fillStyle = "red";
        ctx.fillRect(160, 80, 30, 10);

      }).exec()
    },