I have several shape definitions stored in files, i.e.
Kinetic.Rect({width : 150,height : 50,stroke : 'black',fill :'#00D2FF',strokeWidth : .5,cornerRadius : 25,name : 'rect'});
This line (among with others) are available through an array. Normally I create this shape as follows:
rect = new Kinetic.Rect({
width: 150,
height: 50,
stroke: 'black',
fill: fill,
strokeWidth: .5,
cornerRadius: 25,
name: 'rect'
});
How I create this shape from an array/string?
(rect = new "string from array[xx]")?
KineticJS shapes (like Rect) are defined using a plain javascript object containing your desired properties.
Note: you're fill definition relies on a variable fill
. Be sure fill
is valid!
// define a rectangle
var rectDefinition1={
width: 150,
height: 50,
stroke: 'black',
strokeWidth: .5,
cornerRadius: 25
};
You can feed this definition into a function like this that creates a Kinetic.Rect from your definition and applies a specific new name to that object.
// function to create a Kinetic.Rect from the rectangle definition
function makeRectFromObject(myObject,newName,newFill){
var rect=new Kinetic.Rect(myObject);
rect.name(newName);
rect.fill(newFill);
return(rect);
}
You would use the creation function like this:
// Use like this
var rect1=makeRectFromObject(rectDefinition1,"rect1","red");
// add the newly created rect to the layer and redisplay the layer
layer.add(rect1);
layer.draw();
If you want to store and retrieve your object definitions, you can use JSON:
// serialize your javascript object to a JSON text string
// This is a regular text string that can be stored in a file or database.
var myRectDefinitionAsJSONText = JSON.stringify(rectDefinition1);
// create a javascript object from your JSON text string
var rectDefinition1= JSON.parse( myRectDefinitionAsJSONText );