Frabricjs - Limit Text Input Area

a 夏天 提交于 2019-12-08 05:13:37

问题


I am trying to add some input fields / text area to the canvas.

I would like to somehow set the area where this text could be displayed --> (x,y)-position, width, height of the area. The content should not flow outside the defined area.

Is it possible to automatically change the font-size so that the content fits to the defined area? For example like here: http://www.my-wallsticker.de/index.php?cl=designer&html5=1&text=fabricjs

Here is a part of my code where I add a text field with an area.

var title_input = new fabric.IText('Custom Text', {
                fontFamily: 'arial black',
                fontStyle: 'normal',
                fontSize: $j('#configurator-fontsize').val(),
                fill: 'red',
                hasControls: false,
                lockMovementX: true,
                lockMovementY: true,
                centerTransform: true,
                left: 0,
                top: 0

});

var placeholder_title_input = new fabric.Rect({
                angle: 0,
                backgroundColor: 'transparent',
                fill: 'transparent',
                borderColor: '#000',
                originX: 'center',
                originY: 'center',
                selectable: true,
                width: 300,
                height: 90

});

var title_group = new fabric.Group([placeholder_title_input, title_input], {
                borderColor: '#f00',
                selectable: true,
                lockMovementX: true,
                lockMovementY: true,
                hasControls: false,
                left: zero_position_left + 40,
                top: zero_position_top - 60

});

canvas.add(title_group);    

The whole code is found under my jsfiddle.

I also noticed that my text-align is not working how I would like it to work. If I change the align for "title_input" nothing changes. I would like it to align the content inside the given area.

Thank you in advance for all your help.


回答1:


To check if active object is in boundaries, we could define boundary as rect area.

// Define the boundary; TL = top left, BR = bottom right
var TL_x = 0;
var TL_y = 0;
var BR_x = 50;
var BR_y = 50;

var activeObject = canvas.getActiveObject();
var checkFit = activeObject.isContainedWithinRect(new fabric.Point(TL_x, TL_y), new fabric.Point(BR_x, BR_y));
if(checkFit) console.log('In boundary.');
else console.log('Out of boundary.');

Each canvas object is encapsulate in BoundingRect. We can use this to get the width and the height of an element. If we want to check if active object is too wide or too long, we could use

if(activeObject.getBoundingRectWidth() > (BR_x - TL_x)) console.log('Too wide.');
if(activeObject.getBoundingRectHeight() > (BR_y - TL_y)) console.log('Too long.');


来源:https://stackoverflow.com/questions/26123584/frabricjs-limit-text-input-area

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!