前端前端
fabric
算法
jsBlock
styleBlock
svgBlock
工具其他
Vue、React相关
webgl
GitHub
fabric
算法
jsBlock
styleBlock
svgBlock
工具其他
Vue、React相关
webgl
GitHub
  • 元素操作

    • 元素分组
    • 元素定位
    • 元素层级
    • 元素禁止事件
    • 元素选中样式
  • 变换

    • 变换
  • 图片

    • 图片
    • 背景图
  • 基础图形

    • 三角形
    • 圆形
    • 多边形
    • 折线
    • 椭圆
    • 直线
    • 矩形
    • 路径
  • 序列化和反序列化

    • 反序列化
    • 输出JSON
    • 输出png
    • 输出svg
  • 文本

    • 可编辑文本
    • 多行文本
    • 文本
    • 文本省略
    • 文本边框
  • 源码

    • fabric.Canvas
    • fabric.Circle
    • fabric类的继承体系
  • 画布操作

    • 画布拖动和缩放
    • 画布框选样式
  • 示例

    • fabric-echarts-demo
    • 拓扑图一
    • 拓扑图二

文本省略

单行文本 ellipsis 效果

show code

// 文本没有找到框,自定义Text,加上框
export const FabricText = fabric.util.createClass(fabric.Text, {
  type: 'border-text', // 添加一个 type 属性
  // 初始化
  initialize(text, options) {
    this.callSuper('initialize', text, options) // 继承
    return this
  },
  _render(ctx) {
    fabric.Textbox.prototype._render.call(this, ctx)
    if (this.active) return
    const padding = this.padding || 2
    if (this.showTextBoxBorder) {
      const w = this.width + 2 * padding
      const h = this.height + 2 * padding
      const x = -this.width / 2 - padding
      const y = -this.height / 2 - padding
      ctx.beginPath()
      ctx.moveTo(x, y)
      ctx.lineTo(x + w, y)
      ctx.lineTo(x + w, y + h)
      ctx.lineTo(x, y + h)
      ctx.lineTo(x, y)
      ctx.closePath()
      const stroke = ctx.strokeStyle
      ctx.strokeStyle = this.textboxBorderColor
      ctx.stroke()
      ctx.strokeStyle = stroke
    }
  },
})

const draw = (canvas) => {
  const fullText = '鼠标移上去看看,我是很长很长的文本,我省略了很多字'
  const text = new fabric.Text(`${fullText.substring(0, 6)}...`, {
    left: 50,
    top: 50,
    fontSize: 14,
    fill: '#f00',
    fullText,
    shouldTitleSuspend: 1,
  })
  canvas.add(text)
}

// 这里是自定义的 Text
const nameTip = new FabricText('', {
  fill: '#333',
  fontSize: 14,
  backgroundColor: '#fff',
  padding: 2,
  showTextBoxBorder: true,
  textboxBorderColor: '#333',
  left: -9999,
  top: -9999,
})
canvas.add(nameTip)

// 当鼠标移上去的时候
canvas.on('mouse:over', (opt) => {
  const { target, e } = opt
  if (target && target.shouldTitleSuspend === 1) {
    const p = canvas.getPointer(e)
    nameTip.set({
      left: p.x,
      top: p.y + 20,
      text: target.fullText,
    })
    nameTip.bringToFront()
    canvas.renderAll()
  }
})

canvas.on('mouse:out', () => {
  nameTip.set({ left: -9999, top: -9999 })
  canvas.renderAll()
})
Edit this page
最近更新:: 2025/4/24 10:47
Contributors: wu.hui
Prev
文本
Next
文本边框