首页 > 解决方案 > 自定义子类中的 Fabric.js 文本无法正确缩放

问题描述

我需要像对象一样自定义文本框,所以我创建了一个名为 TextQuide 的类。

import { fabric } from "fabric";

interface ITextQuide extends fabric.IRectOptions {
  text?: Partial<fabric.TextOptions>;
  value: string;
}

class TextQuide extends fabric.Rect {
  text: fabric.Text;
  value: string;

  constructor(options: ITextQuide = { value: "placeholder" }) {
    super(options);
    this.type = "textQuide";
    this.value = options.value;
    this.text = new fabric.Text(this.value, options.text);
    this.text.selectable = false;
    this.fill = "transparent";
    this.stroke = "navy";
    this.strokeWidth = 2;
    this.objectCaching = false;
    this.text.objectCaching = false;
  }

  toObject = (propertiesToInclude?: string[]) => ({
    ...super.toObject(propertiesToInclude),
    text: this.text.toObject(propertiesToInclude)
  });
  toSVG = (reviver?: Function) => {
    const rectSvg = super.toSVG(reviver);
    let textSvg = this.text.toSVG();
    this.text.clone((clone: fabric.Object) => {
      clone.set("left", this.left);
      clone.set("top", this.top);
      textSvg = clone.toSVG();
    });
    return rectSvg + textSvg;
  };

  adjustTextWidth = () => {
    const bbox = this.getBoundingRect();
    const { textLines } = this.text;
    let longestLine = 0;
    for (let i = 0; i < textLines.length; i++) {
      longestLine = Math.max(longestLine, this.text.measureLine(i).width);
    }

    if (longestLine > bbox.width) {
      const scale = bbox.width / longestLine;
      console.log(scale);
      this.text.set("scaleX", scale);
      this.text.setCoords();
      this.setCoords();
    }
  };

  _render = (ctx: CanvasRenderingContext2D) => {
    this.text.set("text", this.value);
    this.adjustTextWidth();

    super._render(ctx);
    this.text._render(ctx);
  };
}

fabric.TextQuide = TextQuide;

export default TextQuide;

它基本上只是一个扩展 fabric.Rect 并渲染 Text 的类。

我不太喜欢 fabrics 默认子类化方式的语法,所以我使用了较新的类语法,一切都按计划运行,设置this.text.scaleX.

该代码在理论上有效,并且在导出到 SVG 时看起来是正确的,但无论出于何种原因,它都没有为画布上的文本设置 scaleX。

我在这里复制了一个最小的例子https://codesandbox.io/s/fabric-text-scaling-demo-h6t84

它还有一些其他的东西,比如我在我的应用程序中使用的缩放控制器,以防它们产生影响。

标签: javascriptcanvasfabricjs

解决方案


推荐阅读