The documentation of Fabric JS says they dropped support for setBackgroundObject
and setBackgroundImage
both of which could be set to update the canvas to have a background image:
e.g
canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
backgroundImageOpacity: 0.5,
backgroundImageStretch: false
});
//or the more convoluted:
const rect = new Rect({
left: 0,
top: 0,
width: canvas.width || 0,
height: canvas.height || 0,
fill: "transparent",
opacity: 0,
stroke: "transparent",
strokeWidth: 0,
selectable: false,
hasControls: false,
});
const img = new FabricImage(url, {
crossOrigin: "anonymous",
});
img.scaleToHeight(canvas.width || 0);
img.scaleToWidth(canvas.height || 0);
rect.set("backgroundImage", img);
canvas.setBackgroundObject(rect);
How to do it in V6?
The documentation is not clear in how they expect this to be done:
rm setBackgroundColor, setBackgroundImage, setOverlayColor, setOverlayImage: assign the property directly and render the canvas
Attempts:
// Attempt A: (doesn't update the background)
const img = FabricImage.fromURL(url, { crossOrigin: 'anonymous' });
canvas.set("backgroundImage", img);
canvas.renderAll();
//Attempt B:
// This leads to the error below:
canvas.backgroundImage = FabricImage.fromURL(url, { crossOrigin: 'anonymous' });
canvas.renderAll();
Type ‘Promise<FabricImage<Partial, SerializedImageProps, ObjectEvents>>’ is missing the following properties from type ‘FabricObject<Partial, SerializedObjectProps, ObjectEvents>’: noScaleCache, lockMovementX, lockMovementY, lockRotation, and 223 more.ts(2740)
(property) StaticCanvas.backgroundImage?: FabricObject<Partial, SerializedObjectProps, ObjectEvents>
Background image of canvas instance. since 2.4.0 image caching is active, please when putting an image as background, add to the canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom vale. As an alternative you can disable image objectCaching