How to implement a gauge solid chart in JSF - jsf

I'm new in JSF and I want to add a highchart solid gauge in my jsf page, but I implment the demo code and when I run it, it throws me this...
Error Parsing /index.xhtml: Error Traced[line: 185] El nombre de la entidad debe aparecer inmediatamente después de '&' en la referencia de entidades.
javax.faces.view.facelets.FaceletException: Error Parsing /index.xhtml: Error Traced[line: 185] El nombre de la entidad debe aparecer inmediatamente después de '&' en la referencia de entidades.
this is the code of the index
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/solid-gauge.js"></script>
<div style="width: 600px; height: 400px; margin: 0 auto">
<div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
<div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
</div>
<script type="text/javascript">
$(function () {
var gaugeOptions = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.1, '#55BF3B'], // green
[0.5, '#DDDF0D'], // yellow
[0.9, '#DF5353'] // red
],
lineWidth: 0,
minorTickInterval: null,
tickAmount: 2,
title: {
y: -70
},
labels: {
y: 16
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
}
}
}
};
// The speed gauge
var chartSpeed = Highcharts.chart('container-speed', Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 200,
title: {
text: 'Speed'
}
},
credits: {
enabled: false
},
series: [{
name: 'Speed',
data: [80],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
'<span style="font-size:12px;color:silver">km/h</span></div>'
},
tooltip: {
valueSuffix: ' km/h'
}
}]
}));
// The RPM gauge
var chartRpm = Highcharts.chart('container-rpm', Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 5,
title: {
text: 'RPM'
}
},
series: [{
name: 'RPM',
data: [1],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y:.1f}</span><br/>' +
'<span style="font-size:12px;color:silver">* 1000 / min</span></div>'
},
tooltip: {
valueSuffix: ' revolutions/min'
}
}]
}));
// Bring life to the dials
setInterval(function () {
// Speed
var point,
newVal,
inc;
if (chartSpeed) {
point = chartSpeed.series[0].points[0];
inc = Math.round((Math.random() - 0.5) * 100);
newVal = point.y + inc;
if (newVal < 0 || newVal > 200) {
newVal = point.y - inc;
}
point.update(newVal);
}
// RPM
if (chartRpm) {
point = chartRpm.series[0].points[0];
inc = Math.random() - 0.5;
newVal = point.y + inc;
if (newVal < 0 || newVal > 5) {
newVal = point.y - inc;
}
point.update(newVal);
}
}, 2000);
});
</script>
</h:body>
</html>
I don't know what I'm doing wrong, hope somebody can help me

JSF using Facelets is based on XML so the ampersands (&) are gonna be taken as an entity instead of the and conditional operator in java and most programming languages. so If you want to use it in your facelets you must change all the & with & which is the ampersand entity.

This problem is caused by not using CData. You should use CDATA for this
//<![CDATA[
//javascript code
//]]>
what does mean CDATA What does <![CDATA[]]> in XML mean?

Related

ZingChart Y Axis Label Formatting

Is it possible in ZingChart to add a secondary y scale that uses the same values as the primary y scale, but just uses a simple conversion (e.g., anomaly degrees Celsius*1.8 = anomaly degrees Fahrenheit).
something like:
var chartConfig = {
scaleY2: { format: %v*1.8 }
}
Or, perhaps a function, like:
var chartConfig = {
scaleY2: { format: 'formatAxis()' }
}
...
formatAxis = function(p){ return { format:p.value*1.8 } }
I'm plotting temperature anomalies in degrees C on the primary y-axis. I'd like the degrees F to show up on the secondary y-axis.
You do indeed use a function. I just had a syntax error.
var chartConfig = {
scaleY2: { format: 'formatAxis()' }
}
...
window.formatAxis = function(v){
return (v*1.8).toFixed(2)+'\u00B0F';
}
The above answer from #magnum-π is correct. Creating a formatting function is the easiest and most effective solution.
// how to call function from ZingChart
let chartConfig = {
scaleY2: { format: 'formatAxis()' }
}
// defining function for ZingChart to find at the window scope
window.formatAxis = function(v){
return (v*1.8).toFixed(2)+'\u00B0F';
}
I have also configured a working demo of this to assist the above answer:
// window.onload event for Javascript to run after HTML
// because this Javascript is injected into the document head
window.addEventListener('load', () => {
// Javascript code to execute after DOM content
// full ZingChart schema can be found here:
// https://www.zingchart.com/docs/api/json-configuration/
let chartConfig = {
type: 'bar',
globals: {
fontSize: '14px',
},
title: {
text: 'Multiple Scales °C vs °F',
fontSize: '24px',
adjustLayout: true,
},
legend: {
draggable: true,
},
// plot represents general series, or plots, styling
plot: {
// hoverstate
tooltip: {
// % symbol represents a token to insert a value. Full list here:
// https://www.zingchart.com/docs/tutorials/chart-elements/zingchart-tokens/
text: '%kl was %v° %plot-text',
borderRadius: '3px',
// htmlMode renders text attribute as html so
// ° is rendered
htmlMode: true
},
valueBox: {
color: '#fff',
placement: 'top-in'
},
// animation docs here:
// https://www.zingchart.com/docs/tutorials/design-and-styling/chart-animation/#animation__effect
animation: {
effect: 'ANIMATION_EXPAND_BOTTOM',
method: 'ANIMATION_STRONG_EASE_OUT',
sequence: 'ANIMATION_BY_NODE',
speed: 275
}
},
plotarea: { margin: 'dynamic',},
scaleX: {
// set scale label
label: {
text: 'Days'
},
// convert text on scale indices
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
scaleY: {
// scale label with unicode character
label: {
text: 'Temperature (°C)'
}
},
scaleY2: {
label: {
text: 'Temperature (°F)'
},
guide: { visible: false }
},
// plot values
series: [
{
text: 'Celcius',
values: [23, 20, 27, 29, 25, 17, 15],
backgroundColor: '#448aff #64b5f6' ,
scales: 'scale-x, scale-y'
},
{
text: 'Farenheit',
values: [35, 42, 33, 49, 35, 47, 35].map(v => Number((v*1.8).toFixed(2))),
backgroundColor: '#ff5252 #e57373',
scales: 'scale-x, scale-y-2'
}
]
};
// render chart
zingchart.render({
id: 'myChart',
data: chartConfig,
height: '100%',
width: '100%',
});
});
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.chart--container {
min-height: 150px;
width: 100%;
height: 100%;
}
.zc-ref {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ZingSoft Demo</title>
<script src="https://cdn.zingchart.com/zingchart.min.js"></script>
</head>
<body>
<!-- CHART CONTAINER -->
<div id="myChart" class="chart--container">
<a class="zc-ref" href="https://www.zingchart.com/">Powered by ZingChart</a>
</div>
</body>
</html>

How to resize svg shape based on text content

I would like to have svg shape scale based on text content of text area or text-input. As the text content increases, the size of the underlying svg element should increase as well
This is what I have so far:
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#myholder'),
width: 1330,
height: 660,
model: graph,
gridSize: 1,
defaultLink: new joint.dia.Link({
attrs: {'.marker-target': {d: 'M 10 0 L 0 5 L 10 10 z'}}
}),
validateConnection: function (cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
// Prevent linking from input ports.
if (magnetS && magnetS.getAttribute('type') === 'input')
return false;
// Prevent linking from output ports to input ports within one element.
if (cellViewS === cellViewT)
return false;
// Prevent loop linking
return (magnetS !== magnetT);
// Prevent linking to input ports.
return magnetT && magnetT.getAttribute('type') === 'input';
},
// Enable marking available cells & magnets
markAvailable: true,
//Enable link snapping within 75px lookup radius
// snapLinks: {radius: 75},
interactive: function (cellView, methodName)
{
if (cellView.model.get('isInteractive') === false)
return false;
// return true;
}
});
joint.shapes.devs.CircleModel = joint.shapes.devs.Model.extend({
markup: '<g class="rotatable"><g class="scalable"><circle class="body"/></g><text class="label"/><g class="inPorts"/><g class="outPorts"/></g>',
// portMarkup: '<g class="port port<%=1%>"><rect class="port-body"/><text class="port-label"/></g>',
defaults: joint.util.deepSupplement({
type: 'devs.CircleModel',
attrs: {
'.body': {r: 50, cx: 50, stroke: '', fill: 'white'},
'.label': {text: '', 'ref-y': 0.5, 'y-alignment': 'middle'},
'.port-body': {r: 3, width: 10, height: 10, x: -5, stroke: 'gray', fill: 'lightgray', magnet: 'active'}
}
}, joint.shapes.devs.Model.prototype.defaults)
});
joint.shapes.devs.CircleModelView = joint.shapes.devs.ModelView;
var rect = new joint.shapes.basic.Rect({
isInteractive: false,
position: {x: 10, y: 50},
size: {width: 51, height: 41},
attrs: {rect: {fill: '#D6F2FC', stroke: '#7E7E7E'}, '.': {magnet: false}}
});
// Create a custom element.
// ------------------------
joint.shapes.html = {};
joint.shapes.html.Element = joint.shapes.basic.Rect.extend({
defaults: joint.util.deepSupplement({
type: 'html.Element',
attrs: {
rect: {stroke: 'none', 'fill-opacity': 0}
}
}, joint.shapes.basic.Rect.prototype.defaults)
});
// Create a custom view for that element that displays an HTML div above it.
// -------------------------------------------------------------------------
joint.shapes.html.ElementView = joint.dia.ElementView.extend({
template: [
'<div class="html-element">',
'<button class="delete">x</button>',
'<span></span>', '<br/>',
// '<input type="text" value="" />',
'<textarea id="txt" type="text" rows="10" value="Start writing"></textarea>',
'</div>'
].join(''),
initialize: function () {
_.bindAll(this, 'updateBox');
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
this.$box = $(_.template(this.template)());
// Prevent paper from handling pointerdown.
this.$box.find('input,select').on('mousedown click', function (evt) {
evt.stopPropagation();
});
this.$ruler = $('<span>', {style: 'visibility: hidden; white-space: pre'});
$(document.body).append(this.$ruler);
// This is an example of reacting on the input change and storing the input data in the cell model.
this.$box.find('textarea').on('input', _.bind(function (evt) {
var val = $(evt.target).val();
this.model.set('textarea', val);
this.$ruler.html(val);
var width = this.$ruler[0].offsetWidth;
var height = this.$ruler[0].offsetHeight;
var area = width * height;
height = area / 150;
width = 150;
if ((area > 9000))
{
this.model.set('size', {width: width + 50, height: height + 80});
this.$box.find('textarea').css({width: width, height: height + 30});
// this.$box.find('.color-edit').css({width: width + 50, height: height + 80});
this.$box.find('.in').css({top: height + 75});
}
}, this));
this.$box.find('textarea').on('click', _.bind(function () {
this.$box.find('.delete').css({opacity: 1});
this.$box.find('textarea').css({opacity: 1});
}, this));
this.$box.find('textarea').on('blur', _.bind(function () {
this.$box.find('.delete').css({opacity: 0});
this.$box.find('textarea').css({opacity: 0});
}, this));
this.$box.find('.delete').on('click', _.bind(this.model.remove, this.model));
// Update the box position whenever the underlying model changes.
this.model.on('change', this.updateBox, this);
// Remove the box when the model gets removed from the graph.
this.model.on('remove', this.removeBox, this);
this.updateBox();
this.listenTo(this.model, 'process:ports', this.update);
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
},
render: function () {
joint.dia.ElementView.prototype.render.apply(this, arguments);
this.paper.$el.prepend(this.$box);
this.updateBox();
return this;
},
updateBox: function ()
{
// Set the position and dimension of the box so that it covers the JointJS element.
var bbox = this.model.getBBox();
// Example of updating the HTML with a data stored in the cell model.
this.$box.find('label').text(this.model.get('label'));
this.$box.find('span').text(this.model.get('select'));
this.$box.css({width: bbox.width + 6, height: bbox.height, left: bbox.x, top: bbox.y, transform: 'rotate(' + (this.model.get('angle') || 0) + 'deg)'});
},
removeBox: function (evt) {
this.$ruler.remove();
this.$box.remove();
}
});
paper.on('cell:pointerdblclick', function (cellView, evt, x, y)
{
var clone = cellView.model.clone();
if (rect.id === cellView.model.id)
{
clone = new joint.shapes.html.Element({
position: {x: 100, y: 60},
size: {width: 81, height: 69},
inPorts: [''],
outPorts: [''],
attrs: {
'.': {magnet: true},
'.label': {text: '', 'ref-x': .4, 'ref-y': .2},
'.inPorts circle': {type: 'input'},
'.outPorts circle': {type: 'output'},
'.port-body': {r: 3}
}
});
// clone.resize(2*81,2*39)
graph.addCell(clone);
}
});
// // First, unembed the cell that has just been grabbed by the user.
paper.on('cell:pointerdown', function (cellView, evt, x, y) {
var cell = cellView.model;
if (!cell.get('embeds') || cell.get('embeds').length === 0) {
// Show the dragged element above all the other cells (except when the
// element is a parent).
cell.toFront();
_.invoke(graph.getConnectedLinks(cell), 'toFront');
}
if (cell.get('parent')) {
graph.getCell(cell.get('parent')).unembed(cell);
}
});
// When the dragged cell is dropped over another cell, let it become a child of the
//element below.
paper.on('cell:pointerup', function (cellView, evt, x, y) {
if (cellView.model.isLink())
return;
var cell = cellView.model;
var cellViewsBelow = paper.findViewsFromPoint(cell.getBBox().center());
if (cellViewsBelow.length) {
// Note that the findViewsFromPoint() returns the view for the `cell` itself.
var cellViewBelow = _.find(cellViewsBelow, function (c) {
return c.model.id !== cell.id;
});
// Prevent recursive embedding.
if (cellViewBelow && cellViewBelow.model.get('parent') !== cell.id) {
cellViewBelow.model.embed(cell);
}
}
});
graph.addCells([rect]);
Could not find a solution elsewhere. Any help would be appreciated. thanks
You have to make the HTML Input resize based on the text inside.
Auto-scaling input[type=text] to width of value?
The ElementView has to listen to the HTML Input changes (input event) and update the size of the model based on the width and height of the HTML Input.
Example:
function onTextInput(evt) {
var $input = $(evt.target);
// 1. auto-scaling the input based on the text inside.
$input.attr('size', Math.max($input.val().length, 10));
// 2. resizing the model to the size of the input + padding.
model.resize($input.outerWidth() + 5, $input.outerHeight() + 40);
}
$('input').on('input', onTextInput);
JS Fiddle: http://jsfiddle.net/kumilingus/Lrffgvqn/
Similar with HTML TextArea, where the only difference will be the way how you auto-scale it based on the text inside.

Creating clickable legends with D3

I'm trying to create a multi-line chart with D3, but I'm stuck on toggling the visibility of lines off. So far, there is only one line, whilst I try to figure it all out (still a bit of a beginner with this), but I can't get the legend to appear, so I can't test if it'll actually get rid of the line too. Here is the JavaScript code:
var BlackBird = [{
"population": "100",
"year": "1970"
}, {
"population": "100.8",
"year": "1971"
}, {
"population": "103.5",
"year": "1972"
}, {
"population": "95.6",
"year": "1973"
}, {
"population": "101.7",
"year": "1974"
}, {
"population": "102",
"year": "1975"
}
];
var vis = d3.select("#visualisation"),
WIDTH = 1110,
HEIGHT = 580,
MARGINS = {
top: 30,
right: 20,
bottom: 20,
left: 50
},
xScale = d3.scale.linear()
.range([MARGINS.left, WIDTH - MARGINS.right])
.domain([1970,2008]),
yScale = d3.scale.linear()
.range([HEIGHT - MARGINS.top, MARGINS.bottom])
.domain([0,300]),
xAxis = d3.svg.axis()
.scale(xScale)
.ticks(25)
.tickFormat(d3.format('0f')),
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(12);
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineGen = d3.svg.line()
.x(function(d) {
return xScale(d.year);
})
.y(function(d) {
return yScale(d.population);
})
.interpolate("basis");
vis.append('path')
.attr('d', lineGen(BlackBird))
.attr('stroke-width', 5)
.attr('fill', 'none')
.attr('opacity', '0.2')
.attr("id", "aline");
vis.append("text")
.attr("x", WIDTH + MARGINS.left +10)
.attr("y", 10)
.attr("class", "legend")
.style("fill", "steelblue")
.on("click", function(){
var active = aline.active ? false : true,
newOpacity = active ? 0 : 1;
d3.select("#aline").attr("opacity", newOpacity);
aline.active = active;
})
.text("Blue Line");
HTML:
<!DOCTYPE html> <html lang= "en"> <head> <meta charset="UTF-8"> <title>D3 Birds</title> <link rel="stylesheet" href="D3Bird2.css"> </head> <body> <svg id="visualisation" width="1140" height="600"></svg> <div id ="BlaBird"> <img src="Blackbird.png" alt="A Blackbird" class= "Birdie"> </div> <script src="d3.min.js" charset="utf-8"> </script> <script src="script2.js" charset="utf-8"></script> </body> </html>
CSS:
.axis path {
fill: none;
stroke: #777;
shape-rendering: crispEdges;
}
.axis text {
font-family: Lato;
font-size: 13px;
}
#aline {
stroke: #000;
opacity: 0.5;
transition: 0.5s;
}
#aline: hover {
opacity: 1;
transition: 0.5s;
}
.Birdie {
transition: 0.5s;
opacity: 0.5;
}
#BlaBird {
position: absolute;
left: 1150px;
top: 30px;
}
.legend {
font-size: 16px;
font-weight: bold;
text-anchor: start;
}
First, you didn't include your HTML markup, but I'm assuming #visualisation is an SVG element. Make sure you've assigned it height and width attributes.
Second, you don't assign a stroke color to your line. I'm assuming you do this in CSS somewhere.
Third, after fixing your variable names, this line:
.attr("x", width + margin.left +10)
is the problem. This pushes the text element outside of it's SVG.
Here's an example where I've fixed some of this up.
EDITS
New problem after looking at your CSS. You are setting the attribute opacity in code, the CSS sets the style opacity. When both are set the browser will use the style. So change your click handler to:
.on("click", function() {
var active = aline.active ? false : true,
newOpacity = active ? 0 : 1;
d3.select("#aline").style("opacity", newOpacity); //<-- set style, not attr
aline.active = active;
})
Example updated.

How to change color of bar in column chart with different level of percentage in highcharts

I want to change the color of the bar column at different percentage. Suppose there are 10 columns to be represented in the column graph. out of which 3 are below 60% and 5 are above 60% and 2 are above 80%. the columns that are below 60% should pick the color green, column that are above 60% should pick up the color amber and those are above 80% should pick red.
Please help me...
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
var chart;
var input = [34.4, 62.5, 80.1, 70, 69.6, 69.5, 89.1, 68.4, 18,
17.3],
data = [],
categories = ['orcl1 ','orcl2 ','orcl3 ','orcl4 ','orcl5 ','orcl6 ','orcl7 ','orcl8 ','orcl9 ','orcl10 '];
$.each(input, function(index, value){
var color;
if (value > 80) color = 'red';
else if (value > 60) color = 'Orange';
else color = 'green';
data.push({y:value, color: color, url:'https://www.google.com'});
});
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'COL',
type: 'column'
},
title: {
text: 'Current Top 10 CPU Consumers',
style: {fontSize: '10px'}
},
xAxis: {
categories: categories,
labels: {
rotation: -35,
align: 'center'
}
},
yAxis: {
title: {
text: 'Percentage',
style: {fontSize: '11px'}
}
},
exporting: { enabled: false },
legend: {
enabled: false,
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b>' +'- Oracle User Process CPU Consumed :'+'<b>'+ this.y +' % ' +'</b>' ;
}
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
location.href = this.options.url;
}
}
}
}
},
series: [{
name: 'CPU Consumed',
pointWidth: 28,
data: data
}]
});
});
});
</script>
</head>
<body>
<script src="../../js/highcharts.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="COL" style="min-width: 100px; height: 300px; margin: 0 auto"></div>
</body>
</html>
You'll need to preprocess the data to assign the colors. Something like this:
var input = [34.4, 62.5, 80.1, 70, 69.6, 69.5, 89.1, 68.4, 18,
17.3],
data = [];
$.each(input, function(index, value){
var color;
if (value > 80) color = 'red';
else if (value > 65) color = 'yellow';
else color = 'green';
data.push({y:value, color: color});
});
http://jsfiddle.net/btwCb/

kinetic javascript get value on click

I have an array of points(pair of x,y) and I draw circles by these points
for (var i = 0; i < points.length;i++){
var circle = new Kinetic.Circle({
x: points[i].x,
y: points[i].y,
radius: 7,
fill: "green",
stroke: "black",
name:i,
strokeWidth: 2
});
circle.on("click", function() {
alert(name); //here I want to get name of circle
});
layer.add(circle);
}
I added new attribute name to each circle, like ID and I want to alert name of circle when mouse is clicked at it.
I am not sure that adding new attribute name to circle is correct.
So,how to add new attribute "name" to circle so that when clicking at circle it alerts its value of name?
Try this below code
<!DOCTYPE HTML>
<html>
<head>
<style>
body
{
margin: 0px;
padding: 0px;
}
</style>
</head>
<body onload="displaycircle()">
<div id="container">
</div>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.0.js"></script>
<script>
function displaycircle() {
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
for (var i = 0; i < 10; i++) {
var circle = new Kinetic.Circle({
x: Math.random() * stage.getWidth(),
y: Math.random() * stage.getHeight(),
radius: 30,
fill: "green",
stroke: "black",
name: i,
strokeWidth: 2,
draggable: true
});
layer.add(circle);
stage.add(layer);
circle.on("click", function() {
alert(this.attrs.name); //here you can get name of circle
});
}
}
</script>
</body>
</html>

Resources