Change sprite text dynamically on chart - javascript

Is there any way to change sprite text dynamically on a chart?
This is not working:
this.lookupReference('chart').setText('Second Text');
Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/1mij

handler: function(){
var chart=this.next();
chart.setSprites({
type: 'text',
reference: 'sprites',
text: 'Second text ',
font: '13px Helvetica bold',
width: 100,
height: 30,
x: 50, // the sprite x position
y: 17 // the sprite y position
});
chart.redraw();
}
here is your forked working fiddle
The chart is made by a canvas, you can't get a specific "piece of the chart" and modify it, so you simply need to redraw the chart with the new text.

Related

Highcharts Donut Chart customization

I'm working with highcharts and aiming to make a chart similar to this:
Now I've been playing around with the whole ordeal for a while now and I've come been able to reach the following point: http://jsfiddle.net/ccjSy/24/
$(function () {
$(document).ready(function () {
var chart = null;
var categories = ['Body Fat', 'Lean Mass'],
name = 'Body Fat vs. Lean Mass',
data = [{
y: 69,
color: '#F0CE0C',
drilldown: {
name: 'Body Fat',
color: '#F0CE0C'
}
}, {
y: 207,
color: '#23A303',
drilldown: {
name: 'Lean Mass' ,
color: '#23A303'
}
}];
// Build the data array
var browserData = [];
for (var i = 0; i < data.length; i++) {
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
}
// Create the chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'donutchart',
type: 'pie',
spacingTop: 0
},
title: {
text: 'Your Body Fat vs Lean Mass',
style: {"color": '#7d7d7d'}
},
series: [{
name: 'Weight',
data: browserData,
dataLabels: {
style: {
fontFamily: 'ArialMT',
fontSize: '15px',
fontWeight: 'bold',
color: '#7d7d7d'
}
},
innerSize: '70%'
}],
tooltip: {
valueSuffix: ' lbs'
},
plotOptions: {
series: {
cursor: 'pointer'
}
}
});
});
});
I am thinking of leaving the space empty in the donut chart and inserting a custom circle with the Weight labeling.
However, I'm not certain how to tackle the following problems:
1) Leave more defined white spaces in between my two columns
2) How to properly align my two data labels? (As you can see in the model, they are in a straight line with neutral lines attached)
3) How to display the data underneath the two labels with both, the pounds and the percentage, as shown in the image.
Answering each of your three questions:
"More white space between columns?" -- add a plotOptions.pie.borderWidth element. The default value is 1. I used 5 to give it more white space.
"Properly align the two data labels?" -- You can compute a custom startAngle based on the two data values which will give you the correct angle to start with. Since you only have two data values in the series, that's easy.
Calculate startAngle for pie chart
var startAngle = 0 - (90 + (180 * (data[0].y / (data[0].y + data[1].y))));
Notice that if you change the y value for the first data object, the "Body Fat" portion of the pie chart will still maintain it's correct position, even as the portion of the chart grows larger or smaller.
"Display data underneath the two labels with custom formatting?" -- use plotOptions.pie.format to apply custom formatting to the pie value labels.
format: '<div style="position: relative; top: -20px; text-align: center">{point.name}<br><b><span style="font-size: 29px">{point.percentage:.0f}%</span></b> ({point.y} lbs)</div>'
Here's a working JSFiddle to see the results. You'll still need to add a dark gray circle behind the pie chart and add the "Total Weight" text but that shouldn't be too difficult.
Since I'm sure you'll be wondering about this, I should mention that there's a lot of white space under the pie chart title because it's leaving enough room for other labels that may appear above or below the pie. Since you're only using two values that will always be on the left/right sides of the pie chart, that doesn't change the fact that HighCharts is preparing to have other labels that may need to be displayed in the surrounding area.

kendo chart legend : label at left, color at right

I have kendo-chart at my js code.
By default, the legend area layout is that, there is list of colors, and the right of every color - there is label with series name. I want to reverse the order: put label first, and color second, and align it to right.
I think the best way to do it is by legend.item, but I don't know how to do it.
see the current state:
and here is demo of what I want will be:
You can create a custom legend visual using the Kendo legend methods.
legend: {
item: {
visual: function (e) {
// get the default color for the legend shape
var color = e.options.markers.background;
// get the default color for the legend text
var labelColor = e.options.labels.color;
// bounds of the legend
var rect = new kendo.geometry.Rect([0, 0], [100, 50]);
var layout = new kendo.drawing.Layout(rect, {
spacing: 5,
alignItems: "center"
});
// Recreate the legend shape (can be any shape)
var marker = new kendo.drawing.Path({
fill: {
color: color
}
}).moveTo(10, 0).lineTo(15, 10).lineTo(5, 10).close();
// recreate the label text
var label = new kendo.drawing.Text(e.series.name, [0, 0], {
fill: {
color: labelColor
}
});
// This is the key part: it draws the label first then the shape
layout.append(label, marker);
layout.reflow()
return layout;
}
}
The important part of this code is this part:
layout.append(label, marker);
Because we're specifying the label first, then the marker, the label should appear first.
I don't have a jsFiddle setup for this, but Kendo has an example in their dojo: http://dojo.telerik.com/OdiNi
In this case you'll have hide the legend.
legend: {
visible: false
},
And create your own legend in html.

canvas fill text vanishes when hovering over chartjs pie chart

I am using a doughnut chart from chartjs, and in the center of this canvas I am filling two lines of text. These show up fine after the initial animation, but when I hover over the doughnut, a tool tip shows up for the relevant element (which is expected), but the fill text vanishes. Any reason why this might be happening and how I can rectify it ?
here is the code I am using to generate the text on the canvas
var pieChart = document.getElementById("pieChart").getContext("2d");
new Chart(pieChart).Doughnut(pieData, {percentageInnerCutout : 80, animationEasing: "easeOutQuart", onAnimationComplete: function() {
pieChart.fillStyle = 'black'
pieChart.font = "50px Roboto";
pieChart.textAlign = "center";
pieChart.fillText(distributionChartData[3]+" %", 135, 120);
pieChart.font = "20px Roboto";
pieChart.fillText((distributionChartData[0]+distributionChartData[1]+distributionChartData[2])+" Responses", 135, 160);
}
});
Here is an image of the chart after initial load
this is the image after hover
Actually you can do this with a simple extension of the chart type you are using and moving your draw code to inside the draw override
Preview
Code
Chart.types.Doughnut.extend({
name: "DoughnutAlt",
draw: function () {
Chart.types.Doughnut.prototype.draw.apply(this, arguments);
this.chart.ctx.textBaseline = "middle";
this.chart.ctx.fillStyle = 'black'
this.chart.ctx.font = "50px Roboto";
this.chart.ctx.textAlign = "center";
this.chart.ctx.fillText(distributionChartData[3] + " %", 135, 120);
this.chart.ctx.font = "20px Roboto";
this.chart.ctx.fillText((distributionChartData[0] + distributionChartData[1] + distributionChartData[2]) + " Responses", 135, 160);
}
});
var pieChart = document.getElementById("pieChart").getContext("2d");
new Chart(pieChart).DoughnutAlt(pieData, {
percentageInnerCutout: 80, animationEasing: "easeOutQuart"
});
Fiddle - http://jsfiddle.net/p979zyLj/
ChartJS will redraw itself as needed (for example when displaying tooltips), so you must redraw your "% and responses" text whenever ChartJS refreshes (redraws) the chart.
You can set ChartJS's 'onAnimationComplete' callback to draw your call your "% and responses" text when ChartJs has completed it's own drawing and animating.
[ Addition: ]
I've taken a look at the ChartJS source code and the Issues on Github.
There is currently no way within the ChartJS API to trigger redraws of your custom text (your "% and responses") after a tooltip closes.
One workaround would be to use CSS to place a div with your "% and responses" over the chart.
I think you can set option: {animation: false} on your Chartjs settings to solve this.

Highlight the corresponding y axis on mouse overr over the bar chart based on that axis in highchart

The process what i am working on it to highlight the y axis , when move the mouse over the barchart which is created based on the y axis.
I have got the ways to make the x axis change color based on the "Bold X-Axis Label on Point Hover in Highcharts Column Chart" but cannot able to apply this to get the y axis change color or make it highlighted.
In the current fiddle i have applied to change the color of the y axis, but cannot remove the color when i move the mouse from the series in the chart which is based on that y axis.
Thanks in Advance.
jsFiddle http://jsfiddle.net/X2t9H/
You would do that the same as you did the title color change:
chart.yAxis[0].update({
title: {
style: {
color: 'red'
}
},
lineColor: 'red',
lineWidth: 1
});
EDIT -
To revert the color do this:
mouseOut: function () {
chart.yAxis[0].update({
title: {
style: {
color: '#89A54E'
}
}
});
}
You had the mouseOut function in there but you didn't populate it.

editable Text option in kinetic js

I want to add Textbox or editable element to give the user the option to edit the text.
This is my current code:
var text = new Kinetic.Text({
text: "Sample Text", ---> i want to edit this text
x: 50,
y: 10,
fill: "transparent",
fontSize: 10,
fontFamily: "Helvetica Neue",
textFill: "#000",
align: "center",
verticalAlign: "middle",
name:'TEXT'
});
At the moment there does not seem to be any way to create editable text with Kinetic JS (see several threads about this at stackoverflow), some people suggest using an input field next to the canvas to edit the text, but my solution would be the following:
create a text with your code
on text click [text.on("click", function...], create an input field right at your mouse cursor
Well, that´s the plan. Maybe it´s easier to use a "save" button text to the input field, so you know exactly when to close it and when to store the input field data to the Kinetic text. you would also need a "close" function if you don´t want to edit it.
A very easy solution would also be a simple JavaScript prompt:
var xy = prompt("gimme your text");
So, something like this would be the best Solution imho:
myText.on('click', function(evt) {
this.setText(prompt('New Text:'));
layer.draw(); //redraw the layer containing the textfield
});
I've made an attempt for an actual KinetiJS plugin with editable text functionality.
I know it's reinventing the wheel, when you can just hover a textarea, but why not have it only in canvas too.
Check the plugin out at: https://github.com/nktsitas/kineticjs-editable-text
I did this some days back on my project. Hare are the code snippets. Basically we first draw the rectangle and then put a text area inside it and finally convert it into kinetic.text node.
drawText: function ( color )
{
var layer1=this.model.stage.getLayers()[0];
var $this=this;
console.log('drawText: color: ' + color);
if($this.rectangleDrawn==true)
{
var down = false, oPoint;
layer1.off("mousedown touchstart mousemove touchmove mouseup touchend");
if(group!=undefined && group!='')
{
$this.hideAnchors(group);
}
console.log("textX: "+textX);
//after rectangle is drawn we now have to add the editablesection
$('<textarea id="text" type="text" width='+textWidth +'px height='+textHeight+'px style="font-size: 30px;font-family:Calibri;height:'+textHeight+'px;width:'+textWidth+'px;position:absolute'+';left:'+textX+'px'+';top:'+textY+'px'+';z-index:5'+';background-color:#ffcc00;"></textarea>')
.insertBefore('.kineticjs-content');
$('#text').on('blur',function()
{
console.log("textchange");
text = new Kinetic.Text( {
x: textX,
y: textY,
stroke: color,
strokeWidth: 1,
fontSize: 30,
fontFamily: 'Calibri',
clearBeforeDraw: false,
name: 'image'+layer1.getName(),
draggable: true,
height: textHeight,
width: textWidth,
text: $('#text').val()
} );
text.on( 'mouseleave dbltap', function ()
{
text=this;
} );
$('#text').remove();
layer1.add( text );
layer1.draw();
})
},drawRectangle: function ( opacity, colorFill,stroke,textColor ){rect = new Kinetic.Rect({
x: mousePos.x,
y: mousePos.y,
width: 0,
height: 0,
stroke: stroke,
strokeWidth: 4,
opacity: opacity,
clearBeforeDraw: false,
name: 'image'+layer1.getName()
});
layer1.on( "mouseup touchend", function ( e )
{
console.log("rectangle: mouseup");
console.log("width: "+rect.getWidth( ));
rect.setOpacity(opacity);
rect.setFill(colorFill);
layer1.draw();
down = false;
console.log("textColor: "+textColor)
if(textColor!=undefined)
{
textWidth=rect.getWidth( );
textHeight=rect.getHeight( );
textX = rect.getAbsolutePosition().x;
textY=rect.getAbsolutePosition().y;
$this.rectangleDrawn=true;
$this.drawText(textColor);
console.log("textdrawn ");
$this.group.remove();
}
},

Categories

Resources