Reputation: 2030
Just started checking out kinetic js. I have many groups, each of which has a Kinetic.Text
and a Kinetic.Rect
.
I can easily change any text by this prompt;
text.on('click', function(evt) {
this.setText(prompt('New Text:'));
layer.draw(); //redraw the layer containing the textfield
});
But i want to change the rectangle's (which encompasses the text ) height and width according to the text. So, this is what I tried, but this doesn't work. It shows me the prompt but doesn't change the text and also my group becomes unclickable after that!;
group.on('click', function(evt) {
this.get('.textbox').setText(prompt('New Text:'));
//this.get('.rectangle')....change rect's height/width here
layer.draw(); //redraw the layer containing the textfield
});
rectangle and textbox are the names for bothe Kinteic.Text
and Kinetic.Rect
in each group. What am I doing wrong?
Upvotes: 0
Views: 993
Reputation: 105035
You can use Kinetic's getTextWidth() to see your text's width. Then adjust the rectangle.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/MZCCA/
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="container"></div>
<button id="fitText">Fit text in the rectangle</button>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.0-beta2.js"></script>
<script>
$("#fitText").click(function(){ redraw();})
function redraw(){
var textWidth=text.getTextWidth();
// redraw the container--add 10px because the text has 5px padding
container.setWidth(textWidth+10);
layer.draw();
}
var stage = new Kinetic.Stage({
container: 'container',
width: 400,
height: 200
});
var layer = new Kinetic.Layer();
var container = new Kinetic.Rect({
x: 100,
y: 30,
width: 75,
height: 30,
fill:"yellow",
stroke: 'black',
strokeWidth: 4,
draggable: true
});
var text = new Kinetic.Text({
x: 100,
y: 30,
text: 'Here is some text.',
fontSize: 18,
fontFamily: 'Calibri',
fill: '#555',
padding: 5,
align: 'center'
});
layer.add(container);
layer.add(text);
stage.add(layer);
</script>
</body>
</html>
Upvotes: 1