I am very new to kineticjs and javascript. I tried to create a function instead of repeating the same blocks of codes.
I have got 6 buttons and this is what i do for 1:
Create a layer
Create the button
Create the text
Add button to the layer
Add text to the layer
Add layer to the stage
Check if button is clicked
Check if text is clicked
Animate the button
Animate the text
I dont want to repeat the same process for the other 5 buttons. How can i create a function and put all of them inside?
When i try i get many errors. Is there anything i am missing?
This is the code i use to create a button:
var layerMenu = new Kinetic.Layer();
var startB = new Kinetic.Rect({ // start button
x: -(800),
//y: stage.height()/4,
y: 260,
width: 200,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
var startT = new Kinetic.Text({ // start text
x: -(800),
y: 270,
text: 'Start the game',
fontSize: 24,
fontFamily: 'Calibri',
width:200 ,
align: 'center',
fill: 'white'
});
layerMenu.add(startB);
layerMenu.add(startT);
stage.add(layerMenu);
startB.on('click', function(evt) {
console.log("start button clicked");
});
startT.on('click', function(evt) {
console.log("start text clicked");
});
var periodM = 400;
var animM = new Kinetic.Animation(function(frame) {
startB.setX(frame.time/periodM + startB.getAttr('x'));
startT.setAttr('x', startB.getAttr('x'));
if (startB.getAttr('x') > (stage.width()/2) -100){
this.stop();
}
}, layerMenu);
Ok I got it sorted,
var layerGame = new Kinetic.Layer();
//// anime menu
var layerMenu = new Kinetic.Layer();
var groupButton = new Kinetic.Group({
x: (stage.width()/2) -100,
y: -200,
width: 220
});
function CreateButton(x, y, text, name)
{
var nButton = new Kinetic.Rect({
x: x,
y: y,
height: 50,
width: 200,
fill: 'green',
stroke: 'black',
strokeWidth: 4
});
var txtButton = new Kinetic.Text({
x: x ,
y: y,
fontFamily: 'Calibri',
fontSize: 24,
height: 50,
padding:10,
width:200 ,
text: text,
align: 'center',
fill: 'white',
name: name
});
groupButton.add(nButton);
groupButton.add(txtButton);
return nButton;
}
var bStart = CreateButton(0, 0, "Start the Game", "StartText");
var bScore = CreateButton(0, 60, "Scores", "ScoreText");
var bHelp = CreateButton(0, 120, "Help", "HelpText");
layerMenu.add(groupButton);
groupButton.get('.StartText').on('click', function(evt) {
console.log("StartText clicked");
});
groupButton.get('.ScoreText').on('click', function(evt) {
console.log("ScoreText clicked");
});
groupButton.get('.HelpText').on('click', function(evt) {
console.log("HelpText clicked");
});
layerMenu.add(groupButton);
stage.add(layerMenu);