在 JSON FabricJS 中包含图像数据

5 javascript json fabricjs

我正在尝试使用 FabricJS 画布,并且想将画布导出为 JSON。

我尝试使用两者加载图像,new fabric.Image并且fabric.Image.fromURL它们都工作得很好。

现在我想从画布获取 JSON。但我想要 2 种 JSON。其中图像的 src 将链接到我最初使用的图像。另一种方法是简单地在 JSON 上添加 Base64 数据。所以我尝试使用canvas.toJSON()and canvas.toDatalessJSON(),但令我惊讶的是,它只是给出了与链接相同的结果,并且它们都不包含图像数据。

如何导出到包含 JSON 上的图像数据的 JSON?(我已经拿到链接了)

我已经将目前为止所拥有的内容整理成了一个小演示。请注意,当您单击“导出”并在控制台上查看时,两个对象都有源链接,但它们实际上都没有 Base64 数据。

我想要 Base64 的原因是因为我希望当我在其他地方重复使用时它能立即得到。

我尝试在互联网上搜索,根据文档,toJSON 应该包含,但看起来它仅适用于形状,而不适用于图像。或者我错过了什么?

提前致谢!

Dur*_*rga 6

扩展到fabric.Image的对象

fabric.Image.prototype.toObject = (function(toObject) {
  return function() {
    return fabric.util.object.extend(toObject.call(this), {
      src: this.toDataURL()
    });
  };
})(fabric.Image.prototype.toObject);
Run Code Online (Sandbox Code Playgroud)

并供 src 使用object.toDataURL()

演示版

fabric.Image.prototype.toObject = (function(toObject) {
  return function() {
    return fabric.util.object.extend(toObject.call(this), {
      src: this.toDataURL()
    });
  };
})(fabric.Image.prototype.toObject);
Run Code Online (Sandbox Code Playgroud)
const useFabricImage = () => {
  const c = document.getElementById("designer");
  const canvas = new fabric.Canvas(c, {width: 500, height: 500})
  const url = "https://i.imgur.com/KxijB.jpg";
  const img = new Image();
  img.src = url;
  const fabricImage = new fabric.Image(img, {});
  canvas.add(fabricImage);
  
  return canvas;
}
const useFromURL = () => {
  const c = document.getElementById("designer");
  const canvas = new fabric.Canvas(c, {width: 500, height: 500})
  const url = "https://i.imgur.com/KxijB.jpg";
  fabric.Image.fromURL(url, (img) => {
    canvas.add(img);
  },{
    crossOrigin:'annonymous'
  });
  return canvas;
}
fabric.Image.prototype.toDatalessObject = fabric.Image.prototype.toObject;

fabric.Image.prototype.toObject = (function(toObject) {
  return function() {
    return fabric.util.object.extend(toObject.call(this), {
      src: this.toDataURL()
    });
  };
})(fabric.Image.prototype.toObject);


const canvas = useFromURL();

const button = document.getElementById("export");
button.addEventListener("click", () => {
  console.log(canvas.toJSON());
  console.log(canvas.toDatalessJSON());
})
Run Code Online (Sandbox Code Playgroud)
#designer {
  border: 1px solid aqua;
}
Run Code Online (Sandbox Code Playgroud)