I'm experimenting with text editing with fabricjs objects and have the following code that works but that I'd like reviewed. My writing feels really clunky to me for some reason and as I'm new to handlers I'm sure what to change if anything?
function addHandler(id, fn, eventName) {
document.getElementById(id)[eventName || 'onclick'] = function() {
var el = this;
if (obj = canvas.getActiveObject()) {
fn.call(el, obj);
canvas.renderAll();
}
};
}
function setStyle(object, styleName, value) {
if (object.setSelectionStyles && object.isEditing) {
var style = { };
style[styleName] = value;
object.setSelectionStyles(style);
}
else {
object[styleName] = value;
}
}
function getStyle(object, styleName) {
return (object.getSelectionStyles && object.isEditing)
? object.getSelectionStyles()[styleName]
: object[styleName];
}
// underline
addHandler('underline', function(obj) {
var isUnderline = (getStyle(obj, 'textDecoration') || '').indexOf('underline') > -1;
setStyle(obj, 'textDecoration', isUnderline ? '' : 'underline');
});
// bold
addHandler('bold', function(obj) {
var isBold = (getStyle(obj, 'fontWeight') || '').indexOf('bold') > -1;
setStyle(obj, 'fontWeight', isBold ? '' : 'bold');
});
// italic
addHandler('italic', function(obj) {
var isItalic = (getStyle(obj, 'fontStyle') || '').indexOf('italic') > -1;
setStyle(obj, 'fontStyle', isItalic ? '' : 'italic');
});
italic
seems to be broken, as you test forfontWeight
instead offontStyle
. And are you sure, thatfontWeight
will always returnbold
, even iffont-weight: 700;
was set in the CSS instead for example? \$\endgroup\$