Position text and circle in Highcharts graph dynamically? - javascript

I want to place a few pieces of text in my graphic. Now, I can do this manually, by specifying the xy coordinates. But this is probably not the best way, as the size of the graph can change, and then the positions are hard coded.
Is there a way to derive in a dynamical way the positions of a line? That is: What is the x/y coordinate of the position x=1980? Here is a fiddle for it.
options.series.push(series);
options.chart.events = {
load: function() {
var chart = this;
chart.renderer.text('1970: Arbitrary chosen reference year: All cumulative values are relative to 1970.', xOffset, yOffset)
.css({
fontSize: '13px',
color: '#aaa',
width: '550px'
})
.add();
chart.renderer.text('1980: observed loss in glacier thickness cumulates to 2 m w.e. since 1970.', 520, 220)
.css({
fontSize: '13px',
color: '#7994d9',
width: '520px'
})
.add();
chart.renderer.text('1990: cumulative ice loss of 4 m w.e.', 690, 255)
.css({
fontSize: '13px',
color: '#ff6c7f',
width: '320px'
})
.add();
}

Maybe this can help you:
var points = chart.series[1].points;
for(var i = 0; i < points.length; i++) {
var point = points[i];
if(point.x === 1980) {
console.log(point.plotX); //263.51049191606
console.log(point.plotY); //40.81559999999999
}
}
UPDATE 1
Adding translated locations to an array:
var locations = [];
var points = chart.series[1].points;
for(var i = 0; i < points.length; i++) {
var point = points[i];
if(point.x === 1980 || point.x === 1990) {
locations.push({
x: point.plotX + chart.yAxis[0].left,
y: point.plotY + chart.yAxis[0].top
});
}
}
Updated fiddle

Related

How to add additional labels to base of columns in Highcharts?

I need two labels for a column, one above to show the score and one below to show if it is a "test" or a "retest". How do I go about doing it?
I assume complicated calculation is needed, something like this? http://jsfiddle.net/72xym/4/ (but I can't really understand)
I got other diagrams need to achieve this as well. Basically I need to do this:
My code is inside here: http://jsfiddle.net/kscwx139/6/
I did this for the part to add the label:
..., function() {
var i = 0, j = 0, len_i, len_j, self = this, labelBBox, labels=[];
for(i=0; i<this.series.length; i++) {
labels[i] = [];
for(j=0; j<this.series[i].data.length; j++) {
labels[i][j] = this.renderer.label(self.series[i].name)
.css({
width: '100px',
color: '#000000',
fontSize: '12px'
}).attr({
zIndex: 100
}).add();
labelBBox = labels[i][j].getBBox();
labels[i][j].attr({
x: 100, //1) what to put here?
y: 100 //2) what to put here?
});
}
}
}
I would do something like this:
var chart2 = new Highcharts.Chart(options2, function() {
var i = 0, j = 0, len_i, len_j, self = this, labelBBox, labels=[], point;
for(i=0; i<this.series.length; i++) {
labels[i] = [];
for(j=0; j<this.series[i].data.length; j++) {
labels[i][j] = this.renderer.label(self.series[i].name)
.css({
width: '100px',
color: '#000000',
fontSize: '12px'
}).attr({
zIndex: 100,
align: "center"
}).add();
point = this.series[i].data[j];
labelBBox = labels[i][j].getBBox();
labels[i][j].attr({
x: point.plotX + this.plotLeft + point.series.pointXOffset + point.shapeArgs.width / 2,
y: this.plotTop + this.plotHeight - labelBBox.height
});
}
}
});
Demo: http://jsfiddle.net/kscwx139/7/
Note: I would suggest using chart.redraw event to update labels position (label[i][j].animate({ x: ..., y: ... });) when resizing browser, updating data, etc.
Short explanation:
point.plotX - x-position in the plotting area (center of the point's shape)
this.plotLeft - left offset for left yAxis (labels, title)
point.series.pointXOffset - offset for multiple columns in the same category
this.plotTop - the same as plotLeft but from top ;)
this.plotHeight - height of the plotting area
labelBBox.height - height of the label to place it above the xAxis line

Tweened Kinetic.js shape doesn't fire most of clicks

Purpose
I'm making a simple "shoot the word" game, where user needs to click on some moving rectangles with words to "shoot" them.
Problem
So i create some objects and move them using simple kinetic.js tweening.
Word creation
function createWord(value){
//here comes some word object construction
var wordGroup = new Kinetic.Group({
x: 0,
y: 0
});
var padding = 10;
wordGroup.label = new Kinetic.Text({
x: padding,
y: padding,
text: value,
fontFamily: 'Times New Roman',
fontSize: 30,
fill: 'white'
});
wordGroup.tag = new Kinetic.Rect({
x: 0,
y: 0,
width: wordGroup.label.width() + (padding << 1),
height: wordGroup.label.height() + (padding << 1),
fill: 'black',
shadowColor: 'black',
shadowBlur: 10,
shadowOffset: {x:10,y:20},
shadowOpacity: 0.5,
cornerRadius: 10
});
wordGroup.add(wordGroup.tag);
wordGroup.add(wordGroup.label);
wordGroup.shoot = function(){ //shooting mechanism (simple stop from moving and remove from scene)
wordGroup.tween.pause();
wordGroup.clean();
dropNextWord(); //drops fresh blood! (new word instead of shooted)
}
wordGroup.clean = function(){ //remove from scene and set it free to drop again
wordGroup.remove();
wordGroup.isActive = false;
}
wordGroup.move = function(callback){ //animates word
wordLayer.add(wordGroup);
moveToSide(wordGroup, callback); //calls moving function
}
wordGroup.on('click', function(e){
wordGroup.shoot();
});
return wordGroup;
}
Tweening part
//move word to opposite side
function moveToSide(word, callback){
var side = Math.random();
var d = 100;
spawnFromSide(word, side); //set random side word position
tweenPosition = {
x: word.x(),
y: word.y()
}
if(side < 0.25){ //left
tweenPosition.x = - d;
} else if(side > 0.25 && side < 0.5){ //right
tweenPosition.x = defaultStageWidth + d;
} else if(side > 0.5 && side < 0.75){ //up
tweenPosition.y = - d;
} else { //down
tweenPosition.y = defaultStageHeight + d;
}
word.tween = new Kinetic.Tween({
node: word,
duration: 4,
easing: Kinetic.Easings.Linear,
x: tweenPosition.x,
y: tweenPosition.y,
onFinish: function(){
word.clean();
callback();
}
});
word.tween.play();
}
But the problem is that click event doesn't fire on large amount of user clicks. As i think, this caused by delayed drawHit() calls inside tweening mechanism, that draws new object position before updating the hit area, so when we shoot object thinking that we hit its current position we miss because its hit area still have the same old position.
Live example
http://jsfiddle.net/hd6z21de/7/
Take a minute on shooting to see this effect in action
Solved this weird behavior by listening canvas touches and check if pointer collide some target word-rect by myself instead of using their own onclick events.
//i listen to canvas because of my app specific, you could simple listen your own layer or even document
$("canvas").bind('click', function(event){
var x = (event.pageX) / stage.scaleX(); //you don't need to divide by scale if your stage isn't scaled as mine does
var y = (event.pageY) / stage.scaleY();
var wordArray = wordGroup.getChildren();
for(var i = 0; i < wordArray.length; i++){ //go through all words and check if we shoot someone (is mouse position included in some word rect)
if(x > wordArray[i].x() &&
y > wordArray[i].y() &&
x < (wordArray[i].x() + wordArray[i].width()) &&
y < (wordArray[i].y() + wordArray[i].height())){
wordArray[i].shoot(); //shoot that word
break;
}
}
}

correct positioning with Highcharts renderer on a bar chart

I have a Highcharts bar chart that I'm trying to add custom shapes to based on the bar values and position. To start with, I'm just trying to use highcharts.renderer.path, to add a line for each bar, as tall as the bar, positioned on the x axis based on a hard coded value. Here's a picture of what I mean:
This should be easy, and it is when the chart.type = "column". In the highcharts callback, I would use getBBox() on each bar, and translate() to convert the x axis value to a pixel value.
However, I've run into several problems when trying to do this with chart.type = "bar". First, all x and y values are switched (I assume this is how the author created the bar chart from a column chart in the first place). This is true for all the properties of the chart as well: plotLeft is now the top, plotTop is now the left.
This should work:
function (chart) {
$.each(chart.series[0].data, function (pointIndex, point) {
var plotLine = {},
elem = point.graphic.element.getBBox(),
yStart,
xStart,
newline;
yStart = chart.plotTop+elem.x;
xStart = chart.plotLeft+elem.height;
plotLine.path = ["M", xStart, yStart+1, "L", xStart, yStart+point.pointWidth];
plotLine.attr = {
'stroke-width': 1,
stroke: point.color,
zIndex: 5
};
newline = chart.renderer.path(plotLine.path).attr(plotLine.attr).add();
});
});
Full example: http://jsfiddle.net/Bh3J4/9/
The second issue may be a bug that can't be overcome. It appears that when there is more than one data point, all of the x and y values get mixed up between the points. Notice in the fiddle that the colors don't match the positions. I've created an issue on GitHub.
When there's just one point, it's not a problem. When there are two points, I could easily switch the values to get the right positioning. However when there are 3 or more points, I can't seem to figure out the logic for how the values get mixed up.
The third issue, is that the translate function doesn't seem to work on the xAxis for a bar chart, even though it does on the yAxis.
chart.yAxis[0].translate(4); // correct for bottom axis
chart.xAxis[0].translate(1); // incorrect for side axis
Is there another way to achieve what I'm looking for? Am I missing something in that Fiddle that's not actually a bug?
I was able to achieve the result I wanted, but I don't know if it's coincidental or a workaround for an actual bug. Regardless, it seems that using the x value from the reverse sorted array helped me line everything up correctly. Here's the callback function for highcharts:
function (chart) {
var benchmarks = { A: 1.5, B: 3.6, C: 2 },
reverseData = _.clone(chart.series[0].data).reverse();
_.each(chart.series[0].data, function (point, pointIndex) {
var plotLine = {},
elem = point.graphic.element.getBBox(),
reverseElem = reverseData[pointIndex].graphic.element.getBBox(),
benchmark = benchmarks[point.category],
yStart = chart.plotTop+reverseElem.x,
xStart = chart.plotLeft+chart.yAxis[0].translate(benchmark),
yEnd = yStart+point.pointWidth-1;
plotLine.path = ["M", xStart, yStart+1, "L", xStart, yEnd];
plotLine.attr = {
'stroke-width': 1,
stroke: "red",
zIndex: 5
};
chart.renderer.path(plotLine.path).attr(plotLine.attr).add();
var margin = 5,
xPadding = 10,
yPadding = 5,
xSplit = xPadding/2,
ySplit = yPadding/2,
text,
box;
text = chart.renderer.text("Top Perf Avg " + benchmark, xStart, yEnd+margin+16).attr({
color: "#646c79",
align: "center",
"font-family": "Arial, sans-serif",
"font-size": 9,
"font-weight": "bold",
style: "text-transform: uppercase",
zIndex: 7
}).add();
box = text.getBBox();
chart.renderer.path(["M", box.x-xSplit, box.y-ySplit,
"l", (box.width/2)+xSplit-margin, 0,
margin, -margin,
margin, margin,
(box.width/2)+xSplit-margin, 0,
0, box.height+yPadding,
-(box.width+xPadding), 0,
0, -(box.height+yPadding)])
.attr({
'stroke-width': 1,
stroke: "#cccccc",
fill: "#ffffff",
zIndex: 6
}).add();
});
}
See the complete working graph here: http://jsfiddle.net/Bh3J4/18/
In the fact, Highcharts rotate everything using transform, so use the same to rotate these lines, see example: http://jsfiddle.net/Bh3J4/19/
function (chart) {
var d = chart.series[0].data,
len = d.length;
for(var i =0; i < len; i++){
var point = d[i],
plotLine = {},
elem = point.graphic.element.getBBox(),
yStart,
xStart,
newline;
console.log(point,point.color);
xStart = point.plotX - point.pointWidth / 2;
yStart = point.plotY;
plotLine.path = ["M", xStart, yStart, "L", xStart+point.pointWidth, yStart];
plotLine.attr = {
transform: 'translate(491,518) rotate(90) scale(-1,1) scale(1 1)',
'stroke-width': 1,
stroke: point.color,
zIndex: 5
};
newline = chart.renderer.path(plotLine.path).attr(plotLine.attr).add();
};
}
Slight adjustment that seems to give precise alignment:
Pls note: changes to calc of xStart/yStart and change to transform translate parameter.
My approach was to make it work for column chart and then get translate refined.
The only unsatisfactory part is that xStart needs: xStart = elem.x+chart.plotLeft; in 'column' mode vs xStart = elem.x; in 'bar' mode...
function (chart) {
var d = chart.series[0].data,
len = d.length;
for(var i =0; i < len; i++){
var point = d[i],
plotLine = {},
elem = point.graphic.element.getBBox(),
yStart,
xStart,
newline;
console.log(point,point.color);
xStart = elem.x;
yStart = chart.plotHeight - (elem.height/2) + chart.plotTop;
plotLine.path = ["M", xStart, yStart, "L", xStart+point.pointWidth, yStart];
plotLine.attr = {
transform: 'translate(542.5,518) rotate(90) scale(-1,1) scale(1 1)',
'stroke-width': 5,
stroke: 'blue',
zIndex: 5
};
newline = chart.renderer.path(plotLine.path).attr(plotLine.attr).add();
};
}

Kineticjs Dragend - How to Store results of getPosition()

I am new to Kineticjs and not a great javascript coder so I am hoping to get some help with this example.
http://jsfiddle.net/pwM8M/
I am trying to store the x axis on doors so when a redraw unrelated to the doors is done they don't go back to the default position. (multiple types of doors and windows too)
Each form element can have multiple quantities (more than one door) so I need a way to store/retrieve the data currently contained in the alert on jsfiddle.
I did some research but have come up empty. Can anyone help with what I have provided?
function OH(x,y,w,h) {
var oh = new Kinetic.Text({
x:x,
y: y,
width: w*scale,
height: h*scale,
stroke: wtc,
strokeWidth: 1,
fill: 'brown',
fontSize: 6,
fontFamily: 'Calibri',
padding:4,
text: w+' x '+h+' OH\n\n<- DRAG ->',
align: 'center',
textFill: 'white',
draggable: true,
dragConstraint:'horizontal',
dragBounds: {
left:xoffset, right: xoffset+width+length-(w*scale)
}
});
oh.on('dragend', function(e) {
alert(oh.getPosition().x);
});
window.south.add(oh);
}
Thanks,
I have fixed sized 40x40 rectangle here in which i am using dragging function. try this
var box = new Kinetic.Rect({
x: parseFloat(area.size.x),
y: parseFloat(area.size.y),
width: 40, //parseFloat(area.size.width)
height: 40,
fill: area.color,
stroke: 'black',
strokeWidth: 1,
opacity: 0.6,
id : area.id + id,
draggable: true,
dragBoundFunc: function(pos) {
// x
var newX = pos.x < 0 ? 40 : pos.x;
var newX = newX > _self.canvasWidth - area.size.width ? _self.canvasWidth - area.size.width : newX;
// y
var newY = pos.y < 0 ? 40 : pos.y;
var newY = newY > _self.canvasHeight - area.size.height ? _self.canvasHeight - area.size.height : newY;
return {
x: newX,
y: newY
};
Use this function
box.on('dragend', function() {
_self.draw = false;
_self.dragArea(area, box);
});
and try this to play with x y coordinates
dragArea: function(area, box){
if(box){
$$('#' + this.formId + ' [name="areas[' + area.id + '][size][x]"]').first().value = parseInt(box.attrs.x);
$$('#' + this.formId + ' [name="areas[' + area.id + '][size][y]"]').first().value = parseInt(box.attrs.y);
area.size.x = parseInt(box.attrs.x);
area.size.y = parseInt(box.attrs.y);
}
},
Create a new array before the function, like so:
var xArray = new Array();
then inside your function
oh.on('dragend', function(e) {
alert(oh.getPosition().x);
// ADD NEW ITEM TO ARRAY, STORE X POSITION
xArray.push(oh.getPosition().x);
});
and so all the x values get stored in the array.
If you need to clear the array, you can simply create a new one again with the same name.
And you can iterate through it with a loop if needed.
updated:
http://jsfiddle.net/pwM8M/2/

accessing a set inside a set in raphael js

I'm in the process of creating a little 'infographic' using raphael js. The infographic will render a number of circles with some text inside. The number of circles isn't know and will depend on the data it gets fed.
I thought that I would organise the raphael objects into sets, one for each circle and then move those sets into one 'container' set but I am having trouble accessing them programatically using something like:
console.log(ss[0].circle);
Here is a snippet of the code im using to draw my circles/add them to a set:
var r = Raphael('raph', '500px', '500px');
var coord = {
'0': {x: 177, y: 75},
'1': {x: 420, y: 173},
'2': {x: 177, y: 415}
};
var ss = r.set();
for(var i=0; i < data.values.length; i++){
var s = r.set();
s.push(r.path("M "+ coord[i].x +" "+ coord[i].y +" L 247 247 z"));
s.push(r.circle(coord[i].x, coord[i].y, 50).attr({fill: '#fff', stroke: '#00adef', 'stroke-width': 2}));
s.push(r.text(coord[i].x, coord[i].y-41).attr({'font': '12px Arial', 'font-weight': 'bold', fill: '#474747', text: data.values[i].name}));
s.push(r.text(coord[i].x, coord[i].y-19).attr({'font': '28px Arial', 'font-weight': 'bold', fill: '#00adef', text: data.values[i].grade}));
ss.push(s);
}
Can someone point me in the right direction?
So let me make sure I understand you correctly:
You want to be able to:
(1) change properties on all of the circles at the same time by updating one set object. For example
ss.translate(10,10)
moves all of the circles 10px right and 10px down.
(2) change properties on individual circles to move the circle (and it's associated path and text elements).
ss[0].move(10, 10)
moves the first circle only.
Does the following accomplish what you want?
var allCircles = r.set();
var circles = [];
for(var i=0; i < data.values.length; i++){
var s = r.set();
s.push(r.path("M "+ coord[i].x +" "+ coord[i].y +" L 247 247 z"));
s.push(r.circle(coord[i].x, coord[i].y, 50).attr({fill: '#fff', stroke: '#00adef', 'stroke-width': 2}));
s.push(r.text(coord[i].x, coord[i].y-41).attr({'font': '12px Arial', 'font-weight': 'bold', fill: '#474747', text: data.values[i].name}));
s.push(r.text(coord[i].x, coord[i].y-19).attr({'font': '28px Arial', 'font-weight': 'bold', fill: '#00adef', text: data.values[i].grade}));
circles.push(s);
for(var j = 0; j < s.length; j++) {
allCircles.push(s[j]);
}
}
You can then move all of the circles at once by:
allCircles.translate(10, 10);
and move an individual circle by:
circles[0].translate(10, 10);
Am I understanding what you're trying to accomplish correctly?
I took bbrame's code and played with it. Two things I learned:
You can have nested sets (a set of sets).
You can refer to the items in a set just like you refer to items in an array...
i.e.,
circle_set[2];
Here's how I tested:
// the set of sets
circ_set = paper.set();
for (i=1; i<21; i++) {
// an empty set
var circ = paper.set();
// add some concentric circles to the set
circ.push(
paper.circle(150+10*i, 50, 9).attr({fill: 'green'}),
paper.circle(150+10*i, 50, 7).attr({fill: 'yellow'}),
paper.circle(150+10*i, 50, 5).attr({fill: 'orange'}),
paper.circle(150+10*i, 50, 3).attr({fill: 'red'})
);
// give all the circles a white outline
circ.attr({stroke: 'white'});
// add each set of circles to a new set (a set of sets)
circ_set.push(circ);
}
// translate a single set of circles
circ_set[0].translate(0,10);
// translate all sets of circles
circ_set.translate(0,10);
Perhaps make the outer set a plane old javascript array, and render each set in a loop.

Categories