Skip to content

Instantly share code, notes, and snippets.

@hervehobbes
Created January 20, 2025 16:16
Show Gist options
  • Save hervehobbes/dae3b610c65772d332b1cf059d203724 to your computer and use it in GitHub Desktop.
Save hervehobbes/dae3b610c65772d332b1cf059d203724 to your computer and use it in GitHub Desktop.
Set a background image to a FabricJs canvas
public onFileChange(files: FileUpload | FileUpload[]): void {
if (files == null) {
return;
}
const canvasElement = this.canvas.getElement();
const width = canvasElement.clientWidth;
const height = canvasElement.clientHeight;
const chosenFile: FileUpload = Array.isArray(files) ? files[0] : files as FileUpload;
const uploadedFile = chosenFile.data;
const reader = new FileReader();
reader.onload = (e) => {
const imageUrl = e.target?.result as string;
fabric.FabricImage.fromURL(imageUrl).then((img) => {
img.set({ left: 0, top: 0 }).scaleToWidth(width);
img.canvas = this.canvas
this.canvas.backgroundImage = img;
this.canvas.renderAll();
});
};
reader.readAsDataURL(uploadedFile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment