fabricjs text高度自适应问题?

新手上路,请多包涵

想要fabricjs text高度随字体变化而变化,就如同css行内元素那样,设置fontSize后不同字体的高度是不同的。

demo:

<template>
  <p class="text-center">fabric</p>
  <div class="w-800px h-200px border-1 border-red border-solid mx-auto">
    <canvas
      class="w-full h-full"
      ref="fabricRef"
    ></canvas>
  </div>
  <p class="text-center mt-50px">css</p>
  <div class="w-808px mx-auto">
    <span class="text-100px font-[黑体] border-1 border-red border-solid">文本</span>
    <span class="text-100px font-[楷体] border-1 border-red border-solid">文本</span>
    <span class="text-100px font-[魏碑] border-1 border-red border-solid">文本</span>
    <span class="text-100px font-[思源] border-1 border-red border-solid">文本</span>
  </div>
</template>

<script setup lang="ts">
import { fabric } from 'fabric'
import { onMounted, ref } from 'vue'

const fabricRef = ref()
const canvas = ref()

async function addFont(fontName, url) {
  const font = new FontFace(fontName, `url("${url}")`)
  await font.load()
  console.log(font)
  document.fonts.add(font)
}

const init = () => {
  const fabricCanvas = new fabric.Canvas(fabricRef.value)
  fabricCanvas.clear()
  fabricCanvas.setWidth(800)
  fabricCanvas.setHeight(200)
  canvas.value = fabricCanvas
}

const createText = (x, y, font) => {
  const text = new fabric.Text('文本', {
    left: x,
    top: y,
    fontFamily: font,
    fontSize: 100,
    fill: '#000',
    stroke: '#fff',
    strokeWidth: 1,
    controls: false,
    hasBorders: true,
    borderColor: 'red',
    lineHeight: 5,
  })
  canvas.value.add(text)
  const rect = new fabric.Rect({
    left: x,
    top: y,
    width: text.width,
    height: text.height,
    fill: 'transparent',
    stroke: '#000'
  })
  canvas.value.add(rect)
  canvas.value.renderAll()
}

onMounted(async () => {
  await addFont('黑体', '/font/黑体.ttf')
  await addFont('楷体', '/font/楷体.ttf')
  await addFont('魏碑', '/font/魏碑字体.ttf')
  await addFont('思源', '/font/思源黑体-B.ttf')
  init()
  createText(0, 10, '黑体')
  createText(200, 10, '楷体')
  createText(400, 10, '魏碑')
  createText(600, 10, '思源')
})
</script>

尝试修改过lineHeight等属性,查看文档也没找到相关属性。求解

阅读 602
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏