Cost Meter Gauge in JavaScript

In this post we will look at the steps we need to make if we want to create this beautiful gauge below:

The gauge is done with MindFusion Charts and Gauges for JavaScript library. You can download the sample together with all needed libraries from this link.

I. Project Setup

We will build the gauge using the OvalGauge library from MindFusion JS Charts and Gauges control. We add two references, needed for the control to work properly:

<script type="text/javascript" src="Scripts/MindFusion.Common.js"></script>
<script type="text/javascript" src="Scripts/MindFusion.Gauges.js"></script>

We have placed those files in a Scripts folder. We will write the JavaScript code for the gauge in a separate file, which we call ValueGauge.js. This file is at the same directory where the web page is. We add a reference to it as well:

<script type="text/javascript" src="ValueGauge.js"></script>

The web page with our sample contains a table. We use the table to place the control together with a text box. The text box is not needed, but we will use it to give the user the option to set the value of the gauge by typing it not only by dragging the pointer.

<table cellpadding="10">
    <tbody>
        <tr>
            <td>Project Cost (in thousands)</td>
        </tr>
        <tr>
            <td><canvas id="value_meter" width="300" height="300"></canvas></td>
        </tr>
        <tr>
            <td>Cost <input id="cost" style="width: 80px"></td>
        </tr>
    </tbody>
</table>

The gauge will be rendered through an HTML Canvas element. The location and size of the Canvas determine the location and the size of the gauge. It is important that we add an id the Canvas – this way we can reference it in the JavaScript code page, which will be necessary.

II. The Control

Now we start editing the ValueGauge.js file and there we first add mappings to the namespaces of Mindusion.Gauges.js that we will use:

/// 
var Gauges = MindFusion.Gauges;

var d = MindFusion.Drawing;
var OvalScale = Gauges.OvalScale;
var Length = Gauges.Length;
var LengthType = Gauges.LengthType;
var Thickness = Gauges.Thickness;
var Alignment = Gauges.Alignment;
var LabelRotation = Gauges.LabelRotation;
var TickShape = Gauges.TickShape;
var PointerShape = Gauges.PointerShape;

The first line is a reference to the Intellisense file that allows us to use code completion of the API members, if supported by our JavaScript IDE.

Now we need to get the DOM Element that corresponds to the gauge Canvas and use it to create an instance of the OvalGauge class:

var value_meter = Gauges.OvalGauge.create(document.getElementById('value_meter'), false);

III. Gauge Scales

Gauge scales depend on the type of the gauge. For oval gauges we use OvalScale The OvalScale needs to be associated with a gauge and here is how we create it:

var valueScale = new Gauges.OvalScale(value_meter);
valueScale.setMinValue(0);
valueScale.setMaxValue(100);
valueScale.setStartAngle(120);
valueScale.setEndAngle(420);

The OvalScale class offers the full set of properties needed to customize the scale. We use the setMinValue and setMaxValue methods to specify the value range o the gauge. The setStartAngle and setEndAngle specify the arc of the gauge and we set them to 120 and 420 respectively. You see that the arc is 300 degrees, which is less than a full circle – exactly how we want it to be.

We continue our customization by setting the fill and stroke of the scale. We actually do not want the default scale to be rendered at all, so we use setFill and setStroke to specify transparent colors:

valueScale.setFill('Transparent');
valueScale.setStroke('Transparent');
valueScale.setMargin(new Gauges.Thickness(0.075, 0.075, 0.075, 0.075, true));

Now we can continue with the ticks. Each gauge can have major, middle and minor ticks. Those ticks are not rendered by default.

var majorSettings = valueScale.majorTickSettings;
majorSettings.setTickShape(Gauges.TickShape.Line);
majorSettings.setTickWidth(new Gauges.Length(10, Gauges.LengthType.Relative));
majorSettings.setTickHeight(new Gauges.Length(10, Gauges.LengthType.Relative));
majorSettings.setFontSize(new Length(14, LengthType.Relative));
majorSettings.setNumberPrecision(0);
majorSettings.setFill('rgb(46, 52, 66)');
majorSettings.setStroke('rgb(46, 52, 66)');
majorSettings.setLabelForeground('rgb(175, 175, 175)');
majorSettings.setLabelAlignment(Alignment.InnerCenter);
majorSettings.setLabelRotation(LabelRotation.Auto);
majorSettings.setLabelOffset(new Length(6, LengthType.Relative));
majorSettings.setStep(20);
majorSettings.setTickAlignment (Alignment.OuterOutside);

We start the customization with the majorTickSettings They will render labels and want to have one tick with a tep of 20. So, we use setStep to specify 20 as an interval and use setTickWidth and setTickHeight to set the size of the ticks. Those properties can be set to an absolute or relative value – see the LengthType enumeration. We also need to change the default shape of the pointer – we use TickShape rest of the settings are intuitive – setFill and setStroke specify how the ticks are colored. We also use setLabelAlignment to position the labels outside the ticks. setTickAlignment is also an important property -it allows us to change the alignment of the ticks, so they can be drawn inside the scale.

The TickSettings object is similar to MajorTickSettings

var middleSettings = valueScale.middleTickSettings;
middleSettings.setTickShape(TickShape.Line);
middleSettings.setTickWidth(new Gauges.Length(10, Gauges.LengthType.Relative));
middleSettings.setTickHeight(new Gauges.Length(10, Gauges.LengthType.Relative));
middleSettings.setTickAlignment (Alignment.OuterOutside);
middleSettings.setShowTicks(true);
middleSettings.setShowLabels(false);
middleSettings.setFill('rgb(46, 52, 66)');
middleSettings.setStroke('rgb(46, 52, 66)');
middleSettings.setCount(5);

We should note here that setShowLabels is false because we want the labels to appear only at intervals of 20. We also use setCount to specify how many ticks we want between each two adjacent major ticks. The rest of the settings are the same as for MajorTickSettings.

IV. Custom Painting

The painting of the colored sections at the edge of the gauge is custom code. The gauges library provides various events that allow the developer to replace the default gauge drawing with custom drawing – see the Events section of the OvalGauge class.

In our sample we will handle two events:

value_meter.addEventListener(Gauges.Events.prepaintBackground, onPrepaintBackground.bind(this));
value_meter.addEventListener(Gauges.Events.prepaintForeground, onPrepaintForeground.bind(this));

prepaintBackground is raised before the background is painted. We can cancel the default painting or add some custom drawing to it. The same is true for prepaintForeground

function onPrepaintBackground(sender, args)
{
	args.setCancelDefaultPainting(true);

	var context = args.getContext();
	var element = args.getElement();
	var bounds = new d.Rect(0, 0, element.getRenderSize().width, element.getRenderSize().height);
        ..................................
}

In the prepaintBackground event handler we first get the handler to the CanvasRenderingContext2D instance. Then we get the bounds of the painted element. This is the inside of the gauge. Each o the colored segments is pained as an arc. We do not create a path figure to fill – instead we set a very thick lineWidth of the stroke:

context.lineWidth = 25;
var correction = context.lineWidth / 2;
	
//light green segment
context.beginPath();
context.strokeStyle = 'rgb(0, 205, 154)';
context.arc(bounds.center().x, bounds.center().y, bounds.width / 2-correction, 0.665*Math.PI, 1*Math.PI, false);	
context.stroke();

We go on painting this way all colored sections of the gauge, only changing the start and end angles. When we are ready we paint the inside of the gauge. We do it with a full arc:

context.beginPath();
bounds.x += 25;
bounds.y += 25;
bounds.width -= 50;
bounds.height -= 50;
context.fillStyle = '#2e3442';

context.arc(bounds.center().x, bounds.center().y, bounds.width / 2, 0*Math.PI, 2*Math.PI, false);
context.fill();

The complete drawing is done inside the prepaintBackground event handler. So, in the prepaintForeground handler we only need to cancel the default painting:

function onPrepaintForeground(sender, args)
{
    args.setCancelDefaultPainting(true);

};

V. The Gauge Pointer

We need to add a Pointer to the OvalScale of the gauge instance if we want to show one:

var pointer = new Gauges.Pointer();
pointer.setFill('white');
pointer.setStroke("#333333");

pointer.setPointerWidth(new Gauges.Length(90, Gauges.LengthType.Relative));
pointer.setPointerHeight(new Gauges.Length(20, Gauges.LengthType.Relative));

pointer.setShape(Gauges.PointerShape.Needle2);
pointer.setIsInteractive(true);

valueScale.addPointer(pointer);

The size of the pointer is also set in LengthType units. This allows us to have the same pointer size relative to the size of the gauge even if we change the size of the Canvas. We use the PointerShape enumeration to specify the type of pointer we want and then we make it interactive with setIsInteractive As an addition to the default needle of the pointer we want to render a circle at the base of the pointer. We do it with custom drawing:

value_meter.addEventListener(Gauges.Events.prepaintPointer, onPrepaintPointer.bind(this));

First we need to handle the prepaintPointer event. In the event handling code we do the drawing:

function onPrepaintPointer(sender, args)
{	
	//args.setCancelDefaultPainting(true);

	var context = args.getContext();
	var element = args.getElement();
	var size = element.getRenderSize();
	var psize = new d.Size(0.2 * size.width, size.height);

	context.save();
	context.transform.apply(context, element.transform.matrix());

	context.beginPath();
	context.arc(psize.width / 2, psize.height / 2, psize.height*0.75, 0, 2 * Math.PI, false);
	var fill = element.getFill();
	context.fillStyle = Gauges.Utils.getBrush(context, fill, new d.Rect(0, 0, size.width, size.height), false);
	context.fill();
	context.strokeStyle = '#333333';
	context.stroke();

	context.restore();
};

Note that in this case we do not cancel the default painting – we will add to it, rather than replace it. Then we get the CanvasRenderingContext2D and size of the rendered element. What is new here is the transform of the CanvasRenderingContext2D object to the center of the gauge. Then we get the Brush that is used to paint the rest of the pointer and use it to fill the custom part as well. We can set the brush directly, but we prefer to take it from the base element – the Pointer This way if we change settings of the Pointer the color of the custom drawn circle will change automatically as well.

VI. Data Binding

What we would like to do now is bind a change in the text field to the value of the gauge scale. We add a method that does it:

function valueChanged(id)
{
	if (isNaN(this.value)) return;
	var gauge = Gauges.OvalGauge.find(id);
	var pointer = gauge.scales[0].pointers[0];
	pointer.setValue(+this.value);
};

When we call the valueChanged method with the instance of the OvalGauge as an argument, we can get its pointer and set its value to the value of ‘this’. We call the valueChanged in such way, that the ‘this’ reference will be the text field:

var cost = document.getElementById('cost');
cost.onchange = valueChanged.bind(cost, ['value_meter']);

Now when the value changes, the event handler takes the pointer and set its value to the value the user has types.

That is the end of this tutorial. You can download the source code of the sample, together with all MindFusion libraries used from the following link:

Download Value Gauge in JavaScript Source Code

You can use the discussion forum to post your questions, comments and recommendations about the sample or MindFusion charts and gauges.

About MindFusion JavaScript Gauges: A set of two gauge controls: oval and rectangular, with the option to add unlimited nuber of scales and gauges. All gauge elements support complete customization of their appearance. Custom drawing is also possible, where you can replace the default rendering of the gauge element or add to it. The gauge controls include a variety of samples that offer beautiful implementations of the most popular applications of gauges: thermometer, car dashboard, functions, compass, clock, cost meter and more.
Gauges for JavaScript is part of MindFusion charts and Dashboards for JavaScript. Details at https://mindfusion.eu/javascript-chart.html.

Pie Chart with Custom Labels in WinForms

In this tutorial we will build the following pie chart using MindFusion Charts and Gauges for WinForms library:

This is a PieChart with a custom Series class that extends the capabilities of a standard PieSeries We need to create a custom Series class because we want the inner labels to follow a special format and we want the outer labels to be rendered as legend items not near pie pieces.

You can download the source code of the sample together with the MindFusion libraries used from the link at the bottom of the post.

I. General Setup

We create an empty WinForms application in C# with Visual Studio. We create a folder called References and there we copy the MindFusion.*.dll -s that we will need. They are:

MindFusion.Charting.dll
MindFusion.Charting.WinForms.dll
MindFusion.Common.dll

We reference those files in our project: we right-click the References folder in the Solution Explorer and click on “Add Reference”. Then we browse to our local References folder and add the 3 dll-s.

We have installed MindFusion Charts and Gauges from the website: http://mindfusion.eu/ChartWinFormsTrial.zip and now we need only to find the PieChart control, drag and drop it onto the WinForms Form of our application.

II. The Custom Pie Series

When you create a custom series you need to implement the Series interface. You need to declare several methods and properties, and one event. Let’s start with the constructor.

We need our chart to use one array with data and one array with labels. We declare two class variables for that and assign to them the values that we receive for them in the constructor. We name the new class CustomPieSeries:

public class CustomPieSeries : Series
{
	public CustomPieSeries(IList data, IList legendLabels )
	{
		values = data;		
		_legendLabels = legendLabels;

		//sum up all pie data
		total = 0.0;
		for (int i = 0; i < data.Count; i++)
			total += data[i];
	}

	IList values;	
	IList _legendLabels;
        double total = 0L;
}

We have added a new class variable called total. It is needed to keep the sum of all data for the chart. We will use this variable when we calculate the percent value of each pie piece.

The SupportedLabels property of type LabelKinds is the way to set which labels will be rendered by the new series. We want tooltips, inner labels and legend labels. There is no special enum field for legend labels. You just set which labels form the series should be rendered as legend items. We decide to use for this the ZAxisLabel, because it is not drawn anywhere on the pie chart and we won’t see it doubled by the legend labels. So, we say that the chart supports ZAxisLabels and we will tell the series that the ZAxisLabels must be rendered in the legend. We will do this later.

public LabelKinds SupportedLabels
{
	get { return LabelKinds.InnerLabel | LabelKinds.ToolTip | LabelKinds.ZAxisLabel; }
}

The GetLabel method is the place where we must return the correct label according to the type and position of the label, which are provided as arguments.

public string GetLabel(int index, LabelKinds kind)
{
	double percent = (values[index] / total) * 100;
	if (kind == LabelKinds.InnerLabel)
		return percent.ToString("F2") + "%\n" + values[index].ToString();
	if (kind == LabelKinds.ToolTip)
		return "Number of interns: " + values[index].ToString("F0") + 
			"\nPercent of total: " + percent.ToString("F2") + "%";

	if (kind == LabelKinds.ZAxisLabel)
		return _legendLabels[index].ToString();

	return null;
}

Here we have the chance to work over the raw data that we have for the series and return the desired labels as a string. We want the inner label to appear as the data value together with its percent representation. We calculate the percent thanks to the total variable and format it in an appropriate way:

 if (kind == LabelKinds.InnerLabel)
	return percent.ToString("F2") + "%\n" + values[index].ToString();

We do the same with the tooltips. We add an explanation text to the tooltip of each piece:

if (kind == LabelKinds.ToolTip)
	return "Number of interns: " + values[index].ToString("F0") + 
		"\nPercent of total: " + percent.ToString("F2") + "%";

The ZAxisLabel is the easiest to do. It will be used by the legend and we perform no special formatting upon it – we just return the label corresponding to the given index.

if (kind == LabelKinds.ZAxisLabel)
		return _legendLabels[index].ToString();

Among the other notable members of the Series interface are the Dimensions and Title properties. Dimensions is the property that specifies how many data dimensions the series has. They are 1 for charts that use one array of data, 2 for axes that use X and Y data, and 3 for 3D charts, which need X, Y and Z data. In our case we return 1 as property value because pie charts, just like radar charts, use only one data array.

public int Dimensions
{
	get { return 1; }
}

The Title property returns the Series title. This is an important property but in our case we will not use it. A common use case for Title is to be rendered in legends. We will not render the Series title in the legend, so we return an empty string.

public string Title
{
	get { return ""; }
}

Building the CustomPieSeries is an easy task:

var values = new List { 23, 54, 17, 9 };
pieChart1.Series = new CustomPieSeries(
	values,				
	new List()
	{
		" <1 month", " <=3 months", " <=6 months", " >6 months"
	}
);

We create a new instance of our new class and assign it to the Series property of the PieChart control. We provide a list with the data and the labels that we want to appear as a legend.

III. The Legend

The legend in the PieChart control is regulated by the LegendRenderer property. We set the ShowSeriesElements property to true to let the chart know that we want the data from the series to be rendered as labels and not the title:

pieChart1.LegendRenderer.ShowSeriesElements = true;

Then we use the ElementLabelKind property to specify which labels we want to use in the legend. These are the ZAxisLabels:

pieChart1.LegendRenderer.ElementLabelKind = LabelKinds.ZAxisLabel;

The other properties are self-explanatory. We use the Title property to set the legend title and set a transparent brush for both the Background and the BorderStroke = “Duration”;

pieChart1.LegendRenderer.Background = new SolidBrush(Color.Transparent);
pieChart1.LegendRenderer.BorderStroke = new SolidBrush(Color.Transparent);

IV. Styling

Styling the chart is done through the Theme property and through styles. There are different style classes available and in our case we will use the PerElementSeriesStyle class. This class accepts as arguments for the brushes and strokes lists with lists that contain the brushes. Then, it colors each element in each series with the corresponding brush in the array at the corresponding index. Our PieChart needs just one list with brushes and strokes. The stroke thicknesses are also added as nested arrays:

pieChart1.Plot.SeriesStyle = new PerElementSeriesStyle()
{
	Fills = new List<List>()
	{
		new List()
		{
			new SolidBrush(Color.FromArgb(158, 212, 224)),
			new SolidBrush(Color.FromArgb(187, 236, 247)),
			new SolidBrush(Color.FromArgb(212, 204, 196)),
			new SolidBrush(Color.FromArgb(245, 210, 179))					         }
	},

	Strokes = new List<list>()
	{
		new List()
		{
			new SolidBrush(Color.White)
						
		}
	},
	StrokeThicknesses = new List<list>()
	{
		new List()
		{
			3.0
		}
	}
};

We also set some appearance properties through the Theme field:

pieChart1.Theme.DataLabelsFontSize = 10;
pieChart1.Theme.HighlightStroke = new SolidBrush(Color.FromArgb(237, 175, 120));
pieChart1.Theme.HighlightStrokeThickness = 4;

The HighlightStroke is used to mark the selected chart element by mouse hover. The DataLabelsFontSize is used not only by painting the inner labels but also by painting the labels in the legend.

Finally we set the Title of the chart:

pieChart1.Title = "Internship Statistics";

And that is the end of this tutorial. You can download the code for the chart together with the MindFusion.*.dll libraries used from this link:

Pie Chart with Custom Labels Source Code Download

You can refer to MindFusion helpful support team with any technical questions regarding the WinForms Charts & Gauges control. Use the forum at: https://mindfusion.eu/Forum/YaBB.pl?board=mchart_disc

About MindFusion Charts and Gauges for WinForms: MindFusion Charts and Gauges for WinForms offers a long list of features that enables developer to build any type of chart, gauge or dashboard. The smart API of the library provides the option different chart elements like plots, axes, labels, and series to be combined and arranged in order to build any type of custom looking chart. The library also supports out of the box the most common chart types together with a set of their widely used properties. The gauge control is indispensable part of the library and offers a linear and oval gauge together with a variety of samples that provide you with the most common types of gauges used: clock, compass, thermometer, car dashboard and more. More about MindFusion Charts and Gauges for WinForms at: https://mindfusion.eu/winforms-chart.html.

Appointment Scheduler in JavaScript

In this blog post we will build from scratch an appointment schedule for 4 practitioners. Each appointment is logged with the patient name and contact details. Each appointment can be scheduled in one of 4 rooms. We will also implement a check to see if the room that we want to assign to an appointment is free at the particular time.

You can run the sample online from the link below:

I. Project Setup

The first thing we’ll do is to create a DIV element and assign it an id. The JS Schedule library needs and HTML div element where the timetable will be rendered. We create one:

<div id="calendar" style="height: 100%;width: 100%"></div>

You can position the div element wherever you wish. It’s location and size determine the location and the size of the schedule.

Next, we need to reference the Schedule library file. It is called MindFusion.Scheduling. We reference it at the end of the web page, right after the closing BODY tag:

<script src="scripts/MindFusion.Scheduling.js" type="text/javascript"></script>
<script src="AppointmentSchedule.js" type="text/javascript"></script>

We will write the JavaScript code for the appointment schedule in a separate JS file, which we call AppointmentSchedule. We have added a reference to it as well.

II. Schedule Settings

In the JavaScript code behind file we first create a mapping to the MindFusion.Scheduling namespace and a reference to the Intellisense file:

/// 

var p = MindFusion.Scheduling;

Next, we use the id of the DIV element to create an instance of the Calendar class:

// create a new instance of the calendar
calendar = new p.Calendar(document.getElementById("calendar"));

We set the currentView property of the calendar to CalendarView Timetable:

// set the view to Timetable, which displays the allotment 
// of resources to distinct hours of a day
calendar.currentView = p.CalendarView.Timetable;

We use the timetableSettings property to specify the time range for each day. The starttime and endTime properties set exactly the begin and end of the time interval rendered by the timetable columns. They are measured in minutes, from midnight of the day they refer to. We want the schedule to start from 7 A that is why we set 420 as value to the startTime property – the minutes in 7 hours.

calendar.timetableSettings.startTime = 420;
calendar.timetableSettings.endTime = 1260;

The titleFormat property specifies how the date at each timetable column will be rendered. The format string follows the standard date and time pattern for JavaScript:

calendar.timetableSettings.titleFormat = "dddd d MMM yyyy";
calendar.itemSettings.tooltipFormat = "%s[hh:mm tt] - %e[hh:mm tt] %h (Contact: %d)";

The tooltipFormat follows a custom formatting pattern, used by Js Scheduler. It supports special format strings like:

  • %s for start time
  • %e for end time
  • %h for header e.g. the text of the item header
  • %d for description: the text that was assigned as a description of the appointment.

III. Contacts, Locations and Grouping

The 4 practitioners are instances of the Contact class:

resource = new p.Contact();
resource.firstName = "Dr. Lora";
resource.lastName = "Patterson";
resource.tag = 2;
calendar.schedule.contacts.add(resource);

It is important to add them to the contacts property of the schedule. The rooms where the appointments take place are Location instances:

resource.name = "Room 112";
calendar.schedule.locations.add(resource);

The grouping of the data that is rendered by the timetable is done is a method called group:

function group(value) {
	calendar.contacts.clear();
	if (value == p.GroupType.GroupByContacts) {
		// add the contacts by which to group to the calendar.contacts collection
		calendar.contacts.addRange(calendar.schedule.contacts.items());
	}
	calendar.locations.clear();
	if (value == p.GroupType.GroupByLocations) {
		// add the locations by which to group to the calendar.locations collection
		calendar.locations.addRange(calendar.schedule.locations.items());
	}
	calendar.groupType = value;
}

When we’ve created the locations and contacts, we added them to the locations and contacts collections of the schedule property of the Calendar . Grouping of the appointments is done based on the contacts and locations collections of the Calendar (not the schedule ). That is why in the group method we clear the data from the respective collection and add to it all data from the corresponding collection in the schedule Of course, we must set the groupType property to the appropriate GroupType value.

IV. Appointments

When the user selects a range of cells the new Appointment dialog appears automatically. There they can enter all necessary data. We want to implement check if a given room is free when the user tries to create a new appointment in this room. We will do the check in the handler of the itemCreating event. The itemCreating event is raised when the new item has not been ready yet and the ItemModifyingEventArgs object that is provided to the event handler gives the opportunity to cancel the event:

calendar.itemCreating.addEventListener(handleItemCreating);

function handleItemCreating(sender, args)
{
	var appLocation = args.item.location;
	
	if(appLocation != null )
	{
		if(appLocation.name != "")
		{
			var items = calendar.schedule.items.items();
			for(var i = 0; i < calendar.schedule.items.count(); i++)
			{
				if( items[i].location == null)
					continue;
				
				//if the location is the same as the location of another appointment
				//at that time we cancel the creating of the appointment
				if( items[i].location.name == appLocation.name && 
				overlappingAppointments (args.item, items[i]))
				{
					args.cancel = true;
					alert("The room is already taken");
				}
	
			}
		}
	}
}

We use a helper method called overlappingAppointments, whose only task is to compare the time range of two items and return true if their time span overlaps – entirely or partially.

/* checks if the time allotted to two different appointments overlaps */
function overlappingAppointments(item1, item2)
{
	if( item1.startTime < item2.startTime &&
	    item1.endTime < item2.endTime )
		  return false;
		  
	if( item1.startTime > item2.endTime &&
	    item1.endTime > item2.endTime )
		  return false;	
		  
		  return true;	  		
}

V. Timeline

Our timetable renders one day at a time. When the user wants to add an appointment that is due in 10 days, they will need to do a lot of scrolling. We can solve the problem by adding a date list at the top o the timetable. The list is another Calendar instance and but its currentView is set to CalendarView List.

We first need to add another DIV element that will be used by the constructor of the new Calendar:

Then we create new Calendar object and make it render a list with dates:

datePicker = new p.Calendar(document.getElementById("datePicker"));
datePicker.currentView = p.CalendarView.List;

By default each Calendar renders the current date when it starts. We make it display a succession of 30 days. We want each day to have a prefix that indicates its week day. In addition, we hide the header of the calendar and stop the default “New Appointment” form from rendering when the user clicks on a cell:

datePicker.listSettings.visibleCells = datePicker.listSettings.numberOfCells = 30;
datePicker.listSettings.headerStyle = p.MainHeaderStyle.None;
datePicker.listSettings.generalFormat = "ddd d";
datePicker.useForms = false;

How do we “wire” the selected date in the timeline to the active date in the timetable? We handle the selectionEnd event and there we assign the selected date from the timeline as the active date of the timetable:

function handleSelectionEnd(sender, args) {
	var startDate = args.startTime;
	var endDate = args.endTime;

	// show the selected date range in the timetable
	calendar.timetableSettings.dates.clear();
	while (startDate < endDate) {
		calendar.timetableSettings.dates.add(startDate);
		startDate = p.DateTime.addDays(startDate, 1);
	}
}

A timetable renders those dates, that are added to its dates property. We add just one date – the date that was selected in the list.

Let’s not forget to call the render method once we’ve finished all customizations on both Calendar render the calendar control

calendar.render();
//render the timeline control
datePicker.render();

VI. Styling

The general styling of the two Calendar instances is done with one of the predefined themes of the Js Scheduler library. First, we need to add a reference to the CSS file, where it is defined. We’ve chosen the “pastel” theme, which is defined in pastel.css:


Then we need only to set its name as a plain string to the theme property of the two Calendar instances:

calendar.theme = "pastel";
datePicker.theme = "pastel";

There is one more styling that we want to do: we want the appointments of each practicioner to be colored in a different color. We inspect the styling o the appointment element in the browser and find out that the styling of the items is set by the class mfp-item. We create 4 different sub-classes of mfp-item for the 4 practitioners:

.itemClass0 .mfp-item
		{
			background-color: #03738C !important;
			color: #fff !important;
		}
		.itemClass1 .mfp-item
		{
			background-color: #03A6A6 !important;
			color: #fff !important;
		}
..............

Then we need to assign the correct class to the appointments. We will do this with the cssClass property of Item We handle the itemCreated event where we get information for the appointment that was created:

calendar.itemCreated.addEventListener(handleItemCreated);

function handleItemCreated(sender, args)
{
	var contact = args.item.contacts.items()[0];
	
	if(contact != null )
		args.item.cssClass = "itemClass" + contact.tag;

}

The easiest way to assign the correct CSS class to the item is to assign data that will help us generate the correct style name. We use the tag property of Contact and assign each practitioner an id that mirrors the last letter in the CSS class we should assign to the appointments associated with this contact.

With that our appointment application is finished. You can download the full source code with the libraries and styles used from this link:

Appointment Schedule in JavaScript: Source Code Download

About MindFusion JavaScript Scheduler: MindFusion Js Scheduler is the complete solution for all applications that need to render interactive timetables, event schedules or appointment calendars. Fully responsive, highly customizable and easy to integrate, you can quickly program the JavaScript scheduling library according to your needs. Find out more at https://mindfusion.eu/javascript-scheduler.html

Combination Chart in JavaScript

In this blog post we will use the Charting for JavaScript library to create the chart that you see below:

This is a combination chart has one line series and two bar series drawn in stacks. We will use the Dashboard control to combine the building elements of the chart: data series, legend, axes, title and plot.

I. HTML Setup

We need an HTML Canvas element for the chart to draw itsself onto. It is important that we give it an id. The Canvas element will render the chart and its position and size will determine where and how big the chart will be drawn.

<canvas id="dashboard" style="width: 100%; height: 100%; display: block;"></canvas>

The Dashboard control needs the MindFusion.Charting.js library. We also need the MindFusion.Drawing module for presentation classes like brushes, pens etc. We include reference to these files at the end of the web page, before the closing BODY tag:

<a href="http://Scripts/MindFusion.Common.js">http://Scripts/MindFusion.Common.js</a>
<a href="http://Scripts/MindFusion.Charting.js">http://Scripts/MindFusion.Charting.js</a>

The two library JavaScript files are in a subfolder called Scripts. We prefer to keep the JavaScript code for the combination chart separate from the web page and we include one final JS reference:

<a href="http://CombinationChart.js">http://CombinationChart.js</a>

This is the code-behind file where we will write all code that creates and customizes the combination chart.

II. Creating the Dashboard and General Chart Settings

We add mappings to the chart and drawing namespaces that we want to use. If your IDE supports Intellisense you can also add a reference to the Intellisense file.

/// 
var Charting = MindFusion.Charting;

var Controls = Charting.Controls;
var Collections = Charting.Collections;
var Drawing = Charting.Drawing;
var Components = Charting.Components;

The Dashboard class requires and HTML element in the constructor. We get the Canvas from the web page with the help of its id:

// create the dashboard
var dashboardEl = document.getElementById('dashboard');
dashboardEl.width = dashboardEl.offsetParent.clientWidth;
dashboardEl.height = dashboardEl.offsetParent.clientHeight;
var dashboard = new Controls.Dashboard(dashboardEl);

The Dashboard control is a container for all elements of a dashboard. In order to render a chart, we need a Plot element that can visualize data. We create an instance of the Plot2D class:

var plot = new Charting.Plot2D();
plot.gridType = Charting.GridType.Horizontal;
plot.gridColor1 = plot.gridColor2 = new Drawing.Color.fromArgb(200, 243, 244, 254);

Then we specify that the plot will render a horizontal grid with light gray grid lines. Each Plot2D has a seriesRenderers property that stores all -SeriesRenderer -s that are responsible for drawing correctly the data series according to their type – LineSeries BarSeries PieSeries etc. More about that later.

III. Data Series and Renderers

Each data series is represented by a class that corresponds to its type. MindFusion Charting for JavaScript has a variety of ISeries classes, some of whom can be used in different chart types. We will first use the BarSeries class to create one of the series that render bars:

// data for first bar series
var barSeries1 = new Charting.BarSeries(
		new Collections.List([9, 11, 13, 18, 19, 22, 23, 26, 29, 32, 33, 36, 41, 46, 49, 55, 57, 58, 61, 63]), //y
		null, null,
		new Collections.List(["1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", 
		"2012", "2013", "2014", "2015", "2016", "2017", "2018"]));

The BarSeries constructor requires several arguments. The first one is the data list, the second are lists with the top and inner labels, which we do not use. The last parameter are the labels for the X-axis and we set here the desired labels.

Then we set the title property of the BarSeries – it is important because it will render as a legend item.

barSeries1.title = "Total amount of goods sold";

We create then another series for the top row of bars. We don’t need any labels any more so we use now a simple Series2D instance:

var barSeries2 = new Charting.Series2D(
		new Collections.List([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),//x
		new Collections.List([3, 4, 5, 5, 7, 8, 7, 6, 8, 15, 17, 21, 19, 18, 17, 16, 17, 19, 20, 22]),//y
		null);

barSeries2.title = "Extra production to meet demand";

The series need a SeriesRenderer that can draw them. There are different SeriesRenderer -s for the different types of series. The different SeriesRenderer instances support different ISeries classes.

In our case we want a stack bar chart and we use the BarStackRenderer . Each SeriesRenderer accepts a list with the Series instances it must render. Here is the code for the stack bars:

// draw bars
var barRenderer = new Charting.BarStackRenderer(new Collections.ObservableCollection([barSeries1, barSeries2]));
barRenderer.seriesStyle = new Charting.PerSeriesStyle (new Collections.List([new Drawing.Brush("#230A59"), new Drawing.Brush("#3E38F2")]));
barRenderer.barSpacingRatio = 0.7;

The different SeriesRenderer instances have different sets of properties that allow you to customize how the data series will be drawn. Here we use the barSpacingRatio to specify the thickness of the stack bars.

As we mentioned earlier, the Plot2D class has a seriesRenderers property where we can add the different SeriesRenderer -s that we want to show. We add the BarStackRenderer add graphics to plot
plot.seriesRenderers.add(barRenderer);

The procedure is the same for the line chart. We create another Series2D instance:

// sample data for line graphics
var lineSeries = new Charting.Series2D(
				new Collections.List([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),//x
				new Collections.List([7, 9, 12, 15, 18, 23, 24, 27, 35, 41, 46, 49, 53, 55, 58,  61, 63, 66, 67, 69 ]),//right-y
				null);
lineSeries.title = "Peak demand";

We give it a title and create a LineRenderer that will render this series:

// draw lines
var lineRenderer = new Charting.LineRenderer(
				new Collections.ObservableCollection([lineSeries]));
lineRenderer.seriesStyle = new Charting.UniformSeriesStyle(new Drawing.Brush("#ffffff"), new Drawing.Brush("#ffffff"), 6);

Finally we add the LineRenderer to the seriesRenderers collection of the Plot2D instance.

plot.seriesRenderers.add(lineRenderer);

You might have noticed that we also set the seriesStyle property in both the BarStackRenderer and the LineRenderer classes. This is the property that specifies how the chart series will be painted. There are different classes that derive from SeriesStyle All of them concern a different pattern of applying brushes and pens to the element of a Series We use here an instance of the PerSeriesStyle class that accepts lists with brushes and strokes and applies one consequtive brush and stroke to all elements in the corresponding Series . The LineRenderer uses the UniformSeriesStyle , which accepts just two Brush instances as arguments and applies them to fill and stroke all elements in all Series instances in the SeriesRenderer .

IV. The Axes

The chart axes are instances of the Axis class. We use their min , max and interval properties to specify the numeric data of each of the two axes that our dashboard will have – X and Y:

// create axes
var xAxis = new Charting.Axis();
xAxis.interval = 0;
xAxis.minValue = -1;
xAxis.maxValue = 20;
xAxis.title = "";

// create axes
var yAxis = new Charting.Axis();
yAxis.interval = 10;
yAxis.minValue = 0;
yAxis.maxValue = 100;
yAxis.title = "Cost of goods in mlns of USD";

Then we specify to the Plot2D that the Axis instances we created are its X and Y axes:

plot.yAxis = yAxis;
plot.xAxis = xAxis;

As you might have guessed, the Axis need Renderer-s to render them. They are called respectively XAxisRenderer and YAxisRenderer .

// create renderers for the two axes
var xAxisRenderer = new Charting.XAxisRenderer(xAxis);
xAxisRenderer.margin = new Charting.Margins(0, 0, 0, 10);
xAxisRenderer.labelsSource = plot;
xAxisRenderer.showCoordinates = false;


var yAxisRenderer = new Charting.YAxisRenderer(yAxis);
yAxisRenderer.margin = new Charting.Margins(10, 0, 0, 0);

The renderers have various properties for specifying how the axes will be rendered. We use margin to add some space around the two axes.

Finally, we use the layoutBuilder property of the Dashboard class to create a GridPanel that will correctly measure and arrange all building blocks of our cobination chart:

dashboard.layoutBuilder.createAndAddPlotAndAxes(
		plot, null,
		[yAxisRenderer],
		[ xAxisRenderer ],
		null);

V. The Legend

As we said, the legend items are taken from the title property of each Series . We use a LegendRenderer to render the legend and set some of its properties:

// add legend
var legendRenderer = new Charting.LegendRenderer();
legendRenderer.content = new Collections.ObservableCollection([barRenderer, lineRenderer]);
legendRenderer.background = new Drawing.Brush("#d0d3fb");
legendRenderer.borderStroke = new Drawing.Brush("#BDBFAA");
legendRenderer.showTitle = false;
legendRenderer.horizontalAlignment = Components.LayoutAlignment.Far;

The content property of LegendRenderer allows us to specify a collection of SeriesRenderer instances. This way we can have one legend for series of different kinds. We don’t need a title for our legend, so we set showTitle to false.

The LegendRenderer requires no special positioning in the dashboard layout, so we simple add it to the rootPanel of the Dashboard and let it handle its easure and placement:

dashboard.rootPanel.children.add(legendRenderer);

VI. The Title and Subtitle

The title is an instance of the TextComponent class:

var tc = new Components.TextComponent();
tc.text = "STEADY GROWTH";
tc.fontSize = 20.4;
tc.horizontalAlignment = Components.LayoutAlignment.Near;
tc.margin = new Charting.Margins(100, 10, 0, 0);
dashboard.layoutPanel.children.add(tc);

It has various appearance properties. Just like the LegendRenderer the TextComponent can be added directly to the children of the layoutPanel.

Now that we’ve made all arrangements for the chart let’s not forget to call the draw method that will render the chart on the screen:

dashboard.draw();

That was everything. You can see an online demo of the chart here.

You can download the full source code of this combination chart in JavaScript together with all used libraries from here:

Combination Chart in JavaScript Full Code

About Charting for JavaScript: MindFusion library for interactive charts and gauges. It supports all common chart types including 3D bar charts. Charts can have a grid, a legend, unlimitd number of axes and series. Scroll, zoom and pan are supported out of the box. You can easily create your own chart series by implementing the Series interface.
The gauges library is part of Charting for JavaScript. It supports oval and linear gauge with several types of labels and ticks. Various samples show you how the implement the gauges to create and customize all popular gauge types: car dashboard, clock, thermometer, compass etc. Learn more about Charting and Gauges for JavaScript at https://mindfusion.eu/javascript-chart.html.

Multi Series Line Chart With Custom ToolTips in JavaScript

In this blog post we will build a line chart with 4 different series and custom labels on both axes. The chart renders tooltips with custom formatting. You can see the chart online here:

I. Initial Setup

We start by creating a blank HTML page and there we initialize the HTML Canvas element that will be needed by the Js Chart library.

<canvas id="chart" style="width: 100%; height: 100%; display: block;">

You can initialize the canvas as you want – there are no special requirements as to the size, position, scroll settings or anything else. What is important is that you add an id for that canvas – it will be used by the chart library. At the bottom of the page, right before the closing BODY tag we add a reference to the charting JavaScript files that represent the chart library:

<script type="text/javascript" src="Scripts/MindFusion.Common.js"></script>
<script type="text/javascript" src="Scripts/MindFusion.Charting.js"></script>

We also add a reference to another JavaScript file called LineChartTooltips.js. We haven’t created it yet, but this will be the file that will hold the JavaScript code for our chart.

<script type="text/javascript" src="LineChartTooltips.js">

II. Initializing the Line Chart In the LineChartTooltips JavaScript file we first include a reference to the Intellisense file so we can use code completion.

/// <reference path="Scripts/jspack-vsdoc.js"></reference>

Then we add mappings to the namespaces that we want to use:

var Controls = Charting.Controls;
var Collections = Charting.Collections;
var DateTimeSeries = Charting.DateTimeSeries;
var Drawing = Charting.Drawing;
var ToolTip = Charting.ToolTip;

Now we create the JavaScript chart object. We need a reference to the HTML canvas element, which we get using its id:

var chartEl = document.getElementById('chart');
chartEl.width = chartEl.offsetParent.clientWidth;
chartEl.height = chartEl.offsetParent.clientHeight;

We use the clientWidth and clientHeight properties of the offsetElement for the chart to give the chart its size.

Next we create the LineChart control and set its title and subtitle.

// create the chart
var lineChart = new Controls.LineChart(chartEl);
lineChart.title = "Women as a percentage in all S&E occupations";
lineChart.subtitle = "1993-2010";

III. Labels

The labels for the X and Y axes are set with two lists:

var xlabels = new Collections.List([
    "1993", "1995", "1997", "1999", "2003", "2006",
    "2008", "2010"]);

var ylabels = new Collections.List([
    "0%", "10%", "20%", "30%", "40%", "50%",
    "60%", "70%"]);

By default the labels at the axes are the intervals. We can replace them with the labels of a given chart series by using the supportedLabels property. This property tells the control at which chart element the labels of the series should be rendered – X or Y axis, tooltip, data labels etc. The members are from the LabelKinds enumeration.

The LineChart control uses series that support X and Y values. The best match is the Series2D class. This class supports one list with labels, which are always drawn at the data points. The easiest thing for us to do is to customize the Series2D and make it accept two lists with labels, which we will show them on both axes. Here is how we create the custom class by inheriting from Series2D

SeriesWithAxisLabels = function (xValues, yValues, xLabels, yLabels) {
    this.yLabels = yLabels;
    Charting.Series2D.apply(this, [xValues, yValues, xLabels]);
};

SeriesWithAxisLabels.prototype = Object.create(Charting.Series2D.prototype);

Our custom class is called SeriesWithAxisLabels. It accepts two lists with labels in the constructor. With one of them we call the constructor of the base class. The other we assign to a new property called yLabels.

Now we need to override the getLabel method and return the right label for the X and Y axis.

SeriesWithAxisLabels.prototype.getLabel = function (index, kind) {
    if ((kind & Charting.LabelKinds.XAxisLabel) != 0 && this.labels)
        return this.labels.items()[index];

    if ((kind & Charting.LabelKinds.YAxisLabel) != 0 && this.yLabels)
        return this.yLabels.items()[index];
   
    return "";
};

The getLabel method is responsible for providing the correct label according to the kind of labels that is requested. Here we check if we are asked for a label at the X or Y axis and return the label with the correct index from the xLabels or yLabels arrays. Here is how we create that series, which serves only to provide labels for the axes:

var series0 = new SeriesWithAxisLabels(
    new Collections.List([1, 2, 3, 4, 5, 6, 7, 8]),
    new Collections.List([0, 10, 20, 30, 40, 50, 60, 70]),
    xlabels, ylabels
);
series0.supportedLabels = Charting.LabelKinds.XAxisLabel | Charting.LabelKinds.YAxisLabel;
lineChart.series.add(series0);

Note that the data for the X and Y values of series0 corresponds to the positions on the axes where the labels should be rendered.

IV. Data

The data for the chart is provided by two series. They are also of type Series2D However, we do not want them to render the labels at the data points, which is their default behaviour. We would customize once again the Series2D class and make the labels be used for tooltips and not the data points.

We define a new SeriesWithToolTip class that overrides Series2D

SeriesWithToolTip = function (xValues, yValues, labels) { 
    Charting.Series2D.apply(this, [xValues, yValues, labels]);
};

SeriesWithToolTip.prototype = Object.create(Charting.Series2D.prototype);

The difference is the getLabel method. When asked for a label for the tooltip it returns the label at the given position from the series’ labels list:

SeriesWithToolTip.prototype.getLabel = function (index, kind) {
    if ((kind & Charting.LabelKinds.ToolTip) != 0 && this.labels)
        return this.labels.items()[index];   

    return Charting.Series2D.prototype.getLabel.apply(this, [index, kind]);
};

We create a data series from the SeriesWithToolTip kind this way:

//first series
var series1 = new SeriesWithToolTip(
    new Collections.List([1, 2, 3, 4, 5, 6, 7, 8]),
    new Collections.List([21.3, 21.5, 21.7, 23, 26.3, 26.1, 26.3, 27.5])
);

series1.title = "All S&E occupations";
var tooltips = new Collections.List();

for (let step = 0; step < series1.yData.count(); step++) {
    tooltips.add(series1.title + " for " + xlabels.items()[step] + ": " +
        series1.yData.items()[step] + "%");
}
series1.labels = tooltips;
series1.supportedLabels = Charting.LabelKinds.ToolTip;
lineChart.series.add(series1);

We generate the tooltip in a list, because we want the text to combine data from the xLabels and its yData list.

V. Styling the Chart

the JavaScript Chart library supports several styles to be applied on the chart depending on what you want to achieve. In our case the best choice is the PerSeriesStyle class, which colours all the elements of a Series with the subsequent brush from its strokes and fills collections.

// create line brushes
var firstBrush = new Drawing.Brush("transparent");
var secondBrush = new Drawing.Brush("#EA3F36");
var thirdBrush = new Drawing.Brush("#1A3D95"); 
var fourthBrush = new Drawing.Brush("#717173");
var fifthBrush = new Drawing.Brush("#407D39");

var style = new Charting.PerSeriesStyle();
style.fills = style.strokes = new Collections.List([firstBrush, secondBrush, thirdBrush, fourthBrush, fifthBrush]);
style.strokeDashStyles = new Collections.List([Drawing.DashStyle.Dash, Drawing.DashStyle.Dash,
Drawing.DashStyle.Dash, Drawing.DashStyle.Dash, Drawing.DashStyle.Dash]);
style.strokeThicknesses = new Collections.List([2, 2, 2, 2, 2]);
lineChart.plot.seriesStyle = style;

The PerSeriesStyle class also provides us with properties to specify the DashStyle and the strokeThickness of the brushes.

The styling of the axes and the fonts is done via the properties of the Theme class. Each chart has a theme property of type Theme. You can use it to customize many properties of the chart:

lineChart.legendTitle = "";
lineChart.gridType = Charting.GridType.Horizontal;
lineChart.theme.axisTitleFontSize = 14;
lineChart.theme.axisLabelsFontSize = 12;
lineChart.theme.subtitleFontStyle = Charting.Drawing.FontStyle.Bold;
lineChart.theme.titleFontStyle = Charting.Drawing.FontStyle.Bold;
lineChart.theme.subtitleFontSize = 16;
lineChart.theme.dataLabelsFontSize = 12;

Note the dataLabelsFontSize property here. It regulates the font not only for the data labels but for the labels of the legend. That is why we set it, though we do not render data labels. There are several dataLabels properties like dataLabelsFontName, which customize different aspects of the labels at chart series and legend.

VI. Legend

You can show the legend with showLegend property, which is true by default. The legendTitle property sets the title of the legend, which we set to an epty string. The labels for each series are taken from the series’ title property:

lineChart.legendTitle = "";

series1.title = "All S&E occupations";
.................
series2.title = "Computer/mathematical scientists";
..................
series3.title = "Engineers";

We can customize the background and border of the legend through properties of the theme or the LegendRenderer:

lineChart.legendRenderer.background = new Drawing.Brush("#f2f2f2");
lineChart.legendRenderer.borderStroke = new Drawing.Brush("#c0c0c0");

VII. ToolTips

The tooltips are automatically rendered when the user hovers over a data point. We make the data points visible by setting showScatter to true:

lineChart.showScatter = true;

Then we set different properties of the TooltTip class to achieve the desired look of the tooltips:

ToolTip.brush = new Drawing.Brush("#fafafa");
ToolTip.pen = new Drawing.Pen("#9caac6");
ToolTip.textBrush = new Drawing.Brush("#717173");
ToolTip.horizontalPadding = 6;
ToolTip.verticalPadding = 4;
ToolTip.horizontalOffset = -6;
ToolTip.verticalOffset = -4;
ToolTip.font = new Charting.Drawing.Font("Arial", 12, Charting.Drawing.FontStyle.Bold);

The ToolTip class is a static class and we can set the properties directly.

At the end, we should always call draw() to see the chart correctly rendered on the screen:

lineChart.draw();

You can download the sample with the JavaScript chart libraries and the Intellisense file from this link:

https://mindfusion.eu/samples/javascript/chart/JsLineChartTooltips.zip

About Charting for JavaScript: MindFusion library for interactive charts and gauges. It supports all common chart types including 3D bar charts. Charts can have a grid, a legend, unlimitd number of axes and series. Scroll, zoom and pan are supported out of the box. You can easily create your own chart series by implementing the Series interface.
The gauges library is part of Charting for JavaScript. It supports oval and linear gauge with several types of labels and ticks. Various samples show you how the implement the gauges to create and customize all popular gauge types: car dashboard, clock, thermometer, compass etc. Learn more about Charting and Gauges for JavaScript at https://mindfusion.eu/javascript-chart.html.