Created
January 20, 2025 16:16
-
-
Save hervehobbes/dae3b610c65772d332b1cf059d203724 to your computer and use it in GitHub Desktop.
Set a background image to a FabricJs canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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