merchi_product_editor
Version:
A React component for editing product images using Fabric.js
67 lines (66 loc) • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.addText = void 0;
// add text to the canvas
var fabric_1 = require("fabric");
/**
* Adds an editable text object to the canvas
* @param canvas - The Fabric.js canvas instance
* @param width - The width of the canvas
* @param height - The height of the canvas
* @param defaultText - Optional default text (defaults to "Text")
* @param fontSize - Optional font size (defaults to 24)
* @param fontFamily - Optional font family (defaults to Arial)
*/
var addText = function (canvas, width, height, defaultText, fontSize, fontFamily) {
if (defaultText === void 0) { defaultText = 'Text'; }
if (fontSize === void 0) { fontSize = 24; }
if (fontFamily === void 0) { fontFamily = 'Nunito'; }
if (!canvas)
return null;
try {
// Safe check if canvas is still valid
if (!canvas.getElement() || !canvas.getElement().parentNode) {
return null;
}
// Create a new text object with minimal options
var text_1 = new fabric_1.fabric.IText(defaultText, {
left: width / 2,
top: height / 2,
fontFamily: fontFamily,
fontSize: fontSize,
fill: '#000000',
originX: 'center',
originY: 'center',
selectable: true,
editable: true
});
// Add the text to the canvas
canvas.add(text_1);
// Ensure the text is rendered
canvas.renderAll();
// Make the text active - this is critical
var setActiveTextObject = function () {
try {
// Check if canvas is still valid
if (canvas && canvas.getElement() && canvas.getElement().parentNode) {
canvas.setActiveObject(text_1);
canvas.renderAll();
}
}
catch (err) {
console.error('Error setting active text object:', err);
}
};
// Initial selection
setActiveTextObject();
// Delayed selection to ensure text becomes active
setTimeout(setActiveTextObject, 50);
return text_1;
}
catch (error) {
console.error('Error adding text to canvas:', error);
return null;
}
};
exports.addText = addText;