measureText

29 阅读1分钟
<template>
  <canvas class="" id="canvas" width="1200" height="600">当前浏览器不支持canvas元素,请升级或更换浏览器!</canvas>
</template>

<script setup lang="ts">
onMounted(() => {
  const el = document.querySelector('#canvas') as HTMLCanvasElement
  const ctx = el.getContext('2d') as CanvasRenderingContext2D
  ctx.beginPath()
  ctx.fillStyle = '#00bcd4'
  ctx.fillRect(0, 0, 1200, 600)

  ctx.strokeStyle = 'red'
  ctx.moveTo(600, 0)
  ctx.lineTo(600, 600)
  ctx.stroke()

  const txtLeft = '打西边儿来了一个小伙儿,他叫马骥!Hello World!'

  ctx.fillStyle = 'red'
  ctx.font = '20px Arial'
  ctx.fillText(txtLeft, 50, 50)
  ctx.fillText('字体宽度:' + ctx.measureText(txtLeft).width + '=>Arial', 50, 100)

  ctx.beginPath()
  ctx.fillStyle = 'blue'
  ctx.font = '20px Georgia'
  ctx.fillText(txtLeft, 50, 150)
  ctx.fillText('字体宽度:' + ctx.measureText(txtLeft).width + '=>Georgia', 50, 200)

  ctx.beginPath()
  ctx.fillStyle = 'yellow'
  ctx.font = '20px Verdana'
  ctx.fillText(txtLeft, 50, 250)
  ctx.fillText('字体宽度:' + ctx.measureText(txtLeft).width + '=>Verdana', 50, 300)

  const txtRight = '打西边儿来了一个小伙儿,他叫马骥!'

  ctx.fillStyle = 'red'
  ctx.font = '20px 楷体'
  ctx.fillText(txtRight, 650, 50)
  ctx.fillText('字体宽度:' + ctx.measureText(txtRight).width + '=>楷体', 650, 100)

  ctx.beginPath()
  ctx.fillStyle = 'blue'
  ctx.font = '20px 黑体'
  ctx.fillText(txtRight, 650, 150)
  ctx.fillText('字体宽度:' + ctx.measureText(txtRight).width + '=>黑体', 650, 200)

  ctx.beginPath()
  ctx.fillStyle = 'yellow'
  ctx.font = '20px 仿宋'
  ctx.fillText(txtRight, 650, 250)
  ctx.fillText('字体宽度:' + ctx.measureText(txtRight).width + '=>仿宋', 650, 300)
})
</script>

下载 (1).png