Home » How to wrap text inside rectangle in kinetic.js

How to wrap text inside rectangle in kinetic.js

by ytstudio

Hello, Friends in this blog post we will see, How to wrap text inside a rectangle in kinetic.js. If you are looking to wrap text then you are at the right place. Here is the information regarding How to wrap text inside a rectangle in kinetic.js given below:

How to wrap text inside a rectangle in kinetic.js?

In Kinetic.js, which is a 2D drawing library for HTML5 canvas, you can create a rectangle and wrap text. It can be manually calculating the dimensions of the text and breaking it into lines that fit within the rectangle’s boundaries. Here’s one example of how you can do this:

Here is the code given below

<!DOCTYPE html>
<html>
<head>
<script src=”https://cdn.rawgit.com/konvajs/konva/7.1.4/konva.min.js”></script>
</head>
<body>
<div id=”container”></div>
<script>
var stage = new Konva.Stage({
container: ‘container’,
width: 400,
height: 200,
});

var layer = new Konva.Layer();
stage.add(layer);

var rectangle = new Konva.Rect({
x: 50,
y: 50,
width: 200,
height: 100,
fill: ‘lightgray’,
stroke: ‘black’,
strokeWidth: 2,
});

var text = new Konva.Text({
x: rectangle.x(),
y: rectangle.y(),
width: rectangle.width(),
height: rectangle.height(),
fontSize: 14,
fontFamily: ‘Arial’,
fill: ‘black’,
align: ‘center’,
verticalAlign: ‘middle’,
});

var longText = “This is a long text that needs to be wrapped inside the rectangle.”;

// Manually wrap text
var words = longText.split(‘ ‘);
var lines = [];
var currentLine = words[0];

for (var i = 1; i < words.length; i++) {
var testLine = currentLine + ‘ ‘ + words[i];
var width = text.getTextWidth(testLine);

if (width <= rectangle.width()) {
currentLine = testLine;
} else {
lines.push(currentLine);
currentLine = words[i];
}
}
lines.push(currentLine);

text.text(lines.join(‘\n’));
layer.add(rectangle);
layer.add(text);
layer.draw();
</script>
</body>
</html>

In this example, we can manually calculate the dimensions of the text and break the text into lines that fit within the bounds of the rectangle. The wrapped text is then displayed inside the rectangle using a Konva.Text object.

Note that this is a basic example and may not handle more complex text formatting requirements. If you need more advanced text manipulation, you may want to consider using a more feature-rich text layout library or developing a more sophisticated text wrapping algorithm.

Related Articles