Search code examples
javascriptreactjsfabricjs

Fabric JS changing src of an object to a url


Is it possible to change the src attribute of a fabric js object to a url of a CDN?


{ version: '4.4.0',
  objects:
   [ { type: 'image',
       version: '4.4.0',
       originX: 'left',
       
       ...

       src:'www.cdn.com',

       crossOrigin: null,
       filters: [] },
       



Solution

  • You can change the src property by just editing the src prop to CDN url and when you load json it will load the cdn image,

    or if you want to change the src in editor then you can use the following:

    changeImageSrcToCDN(newSrc, imageObject) { //imageObject is the image being replaced
            var url = newSrc;
            var scaleX = imageObject.scaleX;
            var scaleY = imageObject.scaleY;
            var width = imageObject.width;
            var height = imageObject.height;
            var left = imageObject.left;
            var top = imageObject.top;
    
            imageObject.setSrc(url, (image) => {
                image.left = left;
                image.top = top;
                image.scaleX = scaleX;
                image.scaleY = scaleY;
                image.width = width;
                image.height = height;
                image.setCoords();
                canvas.renderAll();
            }, { width: imageObject.width, height: imageObject.height, crossOrigin: 'anonymous' });
        }