Reputation: 77
I have the following piece of Konva code and I am trying to update the text attribute
var lifePoint = new Konva.Text({
x: 50,
y: 50,
id: 'P1',
text: 'Player Lifepoint: 100',
fontSize: 30
});
After reading the documentation I tried:
// find and change text
const test = layer.find('#P1')[0];
test.setAttr('text', 'changed');
Could anybody possibly tell me what I am doind wrong?
Upvotes: 3
Views: 3439
Reputation: 9535
As per comment from @lavrton, you need to draw the layer again to see the change. See working snippet below - I added a button for fun.
var pts = 100;
// Set up the stage
var stage = new Konva.Stage({
container: 'container',
width: 650,
height: 300
});
// Make a layer and add to the stage
var layer = new Konva.Layer();
stage.add(layer);
// Make a text node and add to stage
var lifePoint = new Konva.Text({
x: 50,
y: 30,
id: 'P1',
text: 'Player Lifepoint: ' + pts,
fontSize: 30
});
layer.add( lifePoint);
layer.draw(); // My favorite to forget !
// When the user gets more life points add them on.
$('#addlife').on('click', function(e){
// find and change text
var text = layer.find('#P1')[0];
pts = pts + 10;
text.setAttr('text', 'Player Lifepoint: ' + pts);
layer.draw(); // remember to redraw the layer to see the change !
})
#container
{
width: 400px;
height: 100px;
border: 1px solid lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/konva/2.4.2/konva.min.js"></script>
<p><button id='addlife'>Add life</button></p>
<div id='container'></div>
Upvotes: 3