Native Implementation
To load a local image onto a Fabric.js canvas as a background, begin by initializing the canvas and handling file input. Due to browser security policies, direct access to file paths is restricted, so we use URL.createObjectURL() to obtain a temporary reference.
<input type="file" id="imageLoader" onchange="loadImage()" />
<canvas id="mainCanvas" width="600" height="600"></canvas>
<script src="https://cdn.jsdelivr.net/npm/fabric@4.6.0/dist/fabric.min.js"></script>
<script>
const loader = document.getElementById('imageLoader');
let fabricCanvas;
window.onload = () => {
fabricCanvas = new fabric.Canvas('mainCanvas');
};
function loadImage() {
const selectedFile = loader.files[0];
if (!selectedFile) return;
const imageUrl = URL.createObjectURL(selectedFile);
fabricCanvas.setBackgroundImage(imageUrl, () => {
fabricCanvas.renderAll();
});
}
</script>
Alternatively, convert the image to Base64 for better serialization compatibility:
fabric.Image.fromURL(imageUrl, (imgInstance) => {
fabricCanvas.setBackgroundImage(imgInstance, () => {
fabricCanvas.renderAll();
});
});
Integration with Vue 3 and Element Plus
Using el-upload, process the uploaded file into a data URL before applying it to the canvas.
<template>
<div>
<el-upload
action="#"
:auto-upload="false"
:on-change="handleFileChange"
:show-file-list="false">
<el-button type="primary">Select Image</el-button>
</el-upload>
<canvas id="vueCanvas" width="600" height="600"></canvas>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { fabric } from 'fabric'
let canvasInstance;
onMounted(() => {
canvasInstance = new fabric.Canvas('vueCanvas');
});
function handleFileChange(file) {
const reader = new FileReader();
reader.onload = () => {
const imageData = reader.result;
canvasInstance.setBackgroundImage(imageData, () => {
canvasInstance.renderAll();
});
};
reader.readAsDataURL(file.raw);
}
</script>
Production Considerations
In real-world applicasions, avoid storing large base64 strings or local blob URLs. Instead, upload the image to a server which returns a public URL. Use this URL when setting the canvas background to ensure consistent rendeirng across different environments.