javascript - 自定义子类中的 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
它还有一些其他的东西,比如我在我的应用程序中使用的缩放控制器,以防它们产生影响。
解决方案
推荐阅读
- php - 当文档根目录更改时,laravel 上的 url 和路径助手
- javascript - react.js / axios - 如何将 csrf 令牌存储在 cookie 中
- python - Numpy 语句而不是双 for 循环
- ios - 如何使用带有 OAuth1 的 Alamofire 验证 URLRequest
- python-3.x - torch.utils.data.dataloader 输出 TypeError: 'module' object is not callable
- serial-port - ATEasy 中的 RS 232 问题
- android - Android Studio 无法识别 UTF-8 编码
- python - 终端不会使用 BeautifulSoup 显示打印响应
- java - ViewPostIme 指针 1/0
- matlab - 为什么Matlab中数组的维数总是大于等于2?