In previous versions of fabric.js I used the getSelectionStyles
in the way it's used in the getStyle
function with great success.
In this case: when I select some text the fontsize-slider
will change to the current value for the first selected character.
But after upgrading to version 2+ it doesn't work anymore. The getStyle
function returns undefined
.
canvas.on('text:selection:changed', onSelectionChanged);
function onSelectionChanged() {
var obj = canvas.getActiveObject();
if (obj.selectionStart>-1) {
$('#fontSize').val(getStyle(obj,'fontSize'));
}
}
function getStyle(object, styleName) {
return (object.getSelectionStyles && object.isEditing)
? object.getSelectionStyles()[styleName] : object[styleName];
}
Here's a working example using fabric.js version 1.7.22. If you change it to the current version it will fail.
How do i use the getSelectionStyles
in version 2? What have changed?
var canvas = new fabric.Canvas('c');
canvas.add(new fabric.IText('Fontsize test'))
canvas.on('text:selection:changed', onSelectionChanged);
$( "#fontSize" ).on("input", function() {
var obj = canvas.getActiveObject();
if (obj) {
setStyle(obj, 'fontSize', $( "#fontSize" ).val());
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 onSelectionChanged() {
var obj = canvas.getActiveObject();
if (obj.selectionStart>-1) {
$('#fontSize').val(getStyle(obj,'fontSize'));
}
}
function getStyle(object, styleName) {
return (object.getSelectionStyles && object.isEditing)
? object.getSelectionStyles()[styleName] : object[styleName];
}
canvas{
border:2px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.3/fabric.min.js"></script>-->
<canvas id='c' width=400 height=120></canvas>
<label for="fontSize" hint="Font size"><a style="font-size:12px;color:#999">T</a><a style="font-size:19px;color:#ccc">T</a></label>
<input type="range" value="" min="1" max="120" step="1" id="fontSize">