微信小程序Canvas画区域以及文本绝对居中

小程序基础库版本

2.19.0,2.8以下可能不适用此方法

wxml

    <canvas type="2d" canvas-id="radarCanvas" id="radarCanvas" style="width: 200rpx; height: 200rpx;">
    </canvas>

js

createCanvas() {
    const query = wx.createSelectorQuery();
    query.select('#radarCanvas').fields({ node: true, size: true }).exec((res) => {
      const canvas = res[0].node;
      const ctx = canvas.getContext('2d');
      canvas.width = 400; // 画布宽度
      canvas.height = 400; // 画布高度
      ctx.strokeStyle = 'white';
      ctx.fillStyle = '#4b75e7';
      ctx.lineWidth = '2';
      ctx.beginPath();
      ctx.moveTo(200, 0);
      ctx.lineTo(400, 200);
      ctx.lineTo(200, 400);
      ctx.lineTo(0, 200);
      ctx.lineTo(200, 0);
      ctx.closePath();
      ctx.stroke();
      ctx.fill();

      ctx.beginPath();
      ctx.moveTo(200, 0);
      ctx.lineTo(300, 200);
      ctx.lineTo(200, 400);
      ctx.lineTo(100, 200);
      ctx.lineTo(200, 0);
      ctx.closePath();
      ctx.stroke();
      ctx.fillStyle = '#9fccfd';
      ctx.fill();
      ctx.textBaseline = "middle";
      ctx.textAlign = "center";
      ctx.fillStyle = "white";
      ctx.font = '90px "微软雅黑"';
            ctx.fillText("20", 200, 200);
    })
  }

效果

效果图

具体的动态数值,通过计算偏移量即可

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容