小程序canvas 2d 使用手

72 阅读1分钟

由于官方文档没写清楚,所以记录一下demo,废话少说直接代码


    // wxml
    <canvas type="2d" id="myCanvas" style="width: 650px; height: 850px;"></canvas>
    // js
   initCanvas(url) {
    if (this._canvas) return;
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({ node: true, size: true })
      .exec(async (res) => {
        const canvas = res[0].node
        this._canvas = res[0].node
        const ctx = this._canvas.getContext('2d')
        // 下面两句若是省略,canvas会是默认的宽高300 x 150
        this._canvas.width = res[0].width;
        this._canvas.height = res[0].height;

        ctx.clearRect(0, 0,  canvas.width, canvas.height);
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        const codeUrl = canvas.createImage();
        codeUrl.src = url; // src可以是'../../images/foo.png'这样的路径,或者网络图https*,或者http://tmp
        let filePath = await new Promise((resolve, reject)=>{
          codeUrl.onload = ()=>{
            resolve(codeUrl)
          }
          codeUrl.onerror = (err)=>{
            reject(err)
          }
        })
        console.log('drawImage', filePath)
        console.log('w x h ', filePath.width, filePath.height)
        ctx.drawImage(filePath, 0, 0, filePath.width, filePath.height, 105, 120, 440, 440);

        let { nickNameCut='', teamNameCut='' } = this.data;
        ctx.textBaseline = "top";
        ctx.textAlign = 'left';
        // 标题
        ctx.font = "28px normal";
        ctx.fillStyle = '#888888';
        ctx.fillText(`腾讯相册管家·团队版`, 192, 60);
        // 用户昵称
        ctx.fillText(`${nickNameCut}邀请你加入团队`, 270, 680);

        // 团队名称
        ctx.font = "34px bold";
        ctx.fillStyle = '#000000';
        ctx.fillText(`${teamNameCut}`, 270, 730);
        
        function drawAvatar(avatarUrl) {
          const headerImg = canvas.createImage();
          headerImg.src = avatarUrl;
          headerImg.onload = () => {
            ctx.save();
            ctx.beginPath()
            
            // 圆心的坐标 x:125 y:730,半径55
            ctx.arc(125, 730, 55, 0, 2 * Math.PI, false)
            ctx.clip()

            ctx.clearRect(0, 0,  canvas.width, canvas.height);
            ctx.fillStyle = '#eeffff';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            ctx.drawImage(headerImg, 70, 675, 110, 110);
            ctx.closePath();
            ctx.restore();
          }
        }

        // 画头像
        let avatarUrl = this.data.avatarUrl || '../../images/bg.png'
        drawAvatar(avatarUrl);

        // 画线
        ctx.strokeStyle = '#E5E5E5';
        ctx.moveTo(60, 610)
        ctx.lineTo(610, 610)
        ctx.stroke();

        ctx.moveTo(220, 665)
        ctx.lineTo(220, 795)
        ctx.stroke();

      })
  },

有趣的是官方文档依然没有更新,使用3d的文档直接报错。 图片支持本地、网络确实方便了不少。 具体的应用:写过一个俄罗斯方块、贪吃蛇, 想要体验的可以搜搜小程序:式神录 预览:

a73cfa68-6130-4d1e-85b7-4585ad71a21f.jpg

f7c0b6d1-b729e005292f09e.jpg