JSFiddle - React, Tailwind, and code Playground

by liyuanqiu

JavaScript

'use strict';

function getCanvas(input) {

  // 字体大小(单位 pt)
  let fontSize = 30; 
  // 行间距
  let rowGap = fontSize / 5;
  // 列间距
  let columnGap = fontSize / 5;

	// 计算canvas所需的宽高
  let canvas = document.createElement('canvas');
  canvas.width = 0;
  canvas.height = 0;
  let ctx = canvas.getContext('2d');
  ctx.font = `${fontSize}pt 楷体`;
  let txtHeight = parseInt(ctx.font);  
  let width = 0;
  let height = 0;
  input.forEach((item) => {
    let txt = `${item.key}: ${item.value}`;
    let txtWidth = ctx.measureText(txt).width;
    //console.log(`txt "${txt}" 长度: ${txtWidth} 高度: ${txtHeight}`);
    height += rowGap + txtHeight;
    let w = columnGap * 2 + txtWidth;
    width = width < w ? w : width;
    //ctx.fillStyle = "#00000000";
    //ctx.fillText(txt, columnGap, height);    
    //console.log('绘画位置 ', columnGap, height);
  });
  height += rowGap;
  
  // 实际绘图
  canvas.width = width;
  canvas.height = height;
  ctx.font = `${fontSize}pt 楷体`;
  width = 0;
  height = 0;
  input.forEach((item) => {
    let txt = `${item.key}: ${item.value}`;
    let txtWidth = ctx.measureText(txt).width;
    console.log(`txt "${txt}" 长度: ${txtWidth} 高度: ${txtHeight}`);
    height += rowGap + txtHeight;
    let w = columnGap * 2 + txtWidth;
    width = width < w ? w : width;
    ctx.fillStyle = "#00000000";
    ctx.fillText(txt, columnGap, height);    
    //console.log('绘画位置 ', columnGap, height);
  });
  
  return canvas;
}

let canvas = getCanvas([ {
	key: '姓名',
  value: '李元秋'
}, {
	key: '距离',
  value: '38.54米'
}, {
	key: '方向',
  value: '西南'
}, {
	key: '姓名',
  value: '李元秋'
} ]);

document.body.appendChild(canvas);