I upgraded the fabric js version to v6+, and create class method was removed in this new version. Changed my code as follows to work with new fabric version:
import * as fabric from "fabric";
import { QRCodeSVG } from "qrcode.react";
import { FabricObjectMetadataOptions } from "../common/interfaces";
import { convertJSXToXMLString } from "../utils";
export class QrCodeObject extends fabric.Group {
static type = "Qrcode";
private element: fabric.FabricObject;
constructor(options: QrCodeObjectProps) {
super([], {
...options,
lockRotation: true,
lockSkewingX: true,
lockSkewingY: true,
});
this.element = {} as fabric.FabricObject;
this.initialize(options);
return this;
}
private async initialize(options: QrCodeObjectProps) {
const svgString = QrCodeObject.toSVGString(options);
this.element = await this.createSVGFromString(svgString, options);
this.add(this.element);
this.lockMiddleControls();
}
private createSVGFromString(
svgString: string,
options: QrCodeObjectProps
): Promise<fabric.FabricObject> {
return new Promise((resolve) => {
fabric.loadSVGFromString(svgString).then((resultSVG) => {
const obj = fabric.util.groupSVGElements(
resultSVG.objects as fabric.FabricObject[],
resultSVG.options
);
obj.set({
metadata: options.metadata,
});
resolve(obj);
});
});
}
static toSVGString({
content,
widthContainer,
level = "L",
bgColor = "#ffffff",
fgColor = "#000000",
}: QrCodeReactProps) {
const svg = QRCodeSVG({
value: content,
size: widthContainer,
level,
bgColor,
fgColor,
});
const xmlString = convertJSXToXMLString(svg);
return xmlString;
}
private lockMiddleControls() {
this.setControlsVisibility({
mt: false,
mb: false,
ml: false,
mr: false,
bl: true,
br: true,
tl: true,
tr: true,
mtr: false,
});
}
toJSON() {
return super.toObject();
}
}
export interface QrCodeReactProps {
content: string;
widthContainer: number;
bgColor?: string;
fgColor?: string;
level?: "L" | "M" | "Q" | "H";
includeMargin?: boolean;
imageSettings?: {
src: string;
height: number;
width: number;
x?: number;
y?: number;
excavate?: boolean;
};
}
export interface QrCodeObjectProps
extends QrCodeReactProps,
Partial<fabric.FabricObjectProps> {
id: string;
name: string;
metadata: FabricObjectMetadataOptions;
content: string;
widthContainer: number;
}
declare module "fabric" {
namespace fabric {
class Qrcode extends QrCodeObject {
constructor(element: any, options: any);
}
}
}
the code working good, the custome componenent render and after I save it with canvas.ToJson() method, but when restore canvas data with the loadFromJSON function, I get the the following error: fabric: No class registered for Qrcode
So far I have not found a way to fix this error.
when call the restore function get the error message: fabric: No class registered for Qrcode
const handlers = {
save: () => {
saveData(canvas?.toJSON());
},
restore: (jsonData: string) => canvas?.loadFromJSON(jsonData, () => {
canvas?.renderAll();
});
};