FlexChart 101

这个页面演示如何开始使用Wijmo的FlexChart控件。

入门

在JavaScript应用中开始使用FlexChart的步骤:

  1. 添加对Wijmo的引用。
  2. 添加标记作为FlexChart的宿主。
  3. 通过JavaScript初始化FlexChart和它的itemSource属性。
  4. 创建一个或多个数据系列,并将它们添加到FlexChart的系列集合。
  5. (可选)添加一些CSS来自定义图表的外观。
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/> <link rel="stylesheet" type="text/css" href="css/wijmo.css" /> <link href="css/app.css" rel="stylesheet" type="text/css" /> <script src="scripts/wijmo.js" type="text/javascript"></script> <script src="scripts/wijmo.input.js" type="text/javascript"></script> <script src="scripts/wijmo.chart.js" type="text/javascript"></script> <script src="scripts/app.js" type="text/javascript"></script> </head> <body> <!-- this is the FlexChart --> <div id="gettingStartChart"></div> </body> </html>
// create FlexChart var gettingStartedChart = new wijmo.chart.FlexChart('#gettingStartedChart'); // initialize FlexChart's properties gettingStartedChart.initialize({ itemsSource: appData, bindingX: 'country', series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads' } ] });
.wj-flexchart { background-color: white; box-shadow: 4px 4px 10px 0px rgba(50, 50, 50, 0.75); height: 400px; margin-bottom: 12px; padding: 8px; }

结果:

图表类型

FlexChart控件有三个属性允许你来自定义图表的类型:

  1. chartType: 对于所有系列对象选择默认的图表类型。个别系列对象可以覆盖它。
  2. stacking: 确定系列对象是否独立地绘制,堆积或百分比堆积。
  3. rotated: 翻转X轴和Y轴,导致X变为垂直,Y变为水平。

以下这个示例让你看见当你改变这些属性的时候发生了什么:

<div id="chartTypes"></div> <select id="typeMenu"> <option value="0" selected="selected">Column</option> <option value="1">Bar</option> <option value="2">Scatter</option> <option value="3">Line</option> <option value="4">LineSymbols</option> <option value="5">Area</option> <option value="9">Spline</option> <option value="10">SplineSymbols</option> <option value="11">SplineArea</option> </select> <select id="stackingMenu"> <option value="0" selected="selected">None</option> <option value="1">Stacked</option> <option value="2">Stacked 100%</option> </select> <select id="rotatedMenu"> <option value="false" selected="selected">False</option> <option value="true">True</option> </select>
// create FlexChart and Menus var chartTypes = new wijmo.chart.FlexChart('#chartTypes'), typeMenu = new wijmo.input.Menu('#typeMenu'), stackingMenu = new wijmo.input.Menu('#stackingMenu'), rotatedMenu = new wijmo.input.Menu('#rotatedMenu'); // initialize FlexChart's properties chartTypes.initialize({ itemsSource: appData, bindingX: 'country', series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads' } ] }); // update the menus' headers updateMenuHeader(typeMenu, 'Chart Type'); updateMenuHeader(stackingMenu, 'Stacking'); updateMenuHeader(rotatedMenu, 'Rotated'); typeMenu.selectedIndexChanged.addHandler(function () { if (typeMenu.selectedValue) { // update FlexChart's chartType chartTypes.chartType = parseInt(typeMenu.selectedValue); // update menu header updateMenuHeader(typeMenu, 'Chart Type'); } }); stackingMenu.selectedIndexChanged.addHandler(function () { if (stackingMenu.selectedValue) { // update FlexChart's stacking property chartTypes.stacking = parseInt(stackingMenu.selectedValue); // update menu header updateMenuHeader(stackingMenu, 'Stacking'); } }); rotatedMenu.selectedIndexChanged.addHandler(function () { if (rotatedMenu.selectedValue) { // specify if chart should be rotated or not chartTypes.rotated = rotatedMenu.selectedValue === 'true'; // update menu header updateMenuHeader(rotatedMenu, 'Rotated'); } }); // helper function for Menu headers function updateMenuHeader(menu, prefix) { menu.header = '<b>' + prefix + '</b>: ' + menu.text; }

结果:

漏斗图

下面的示例演示如何创建和自定义漏斗图:

<div id="funnelChart"></div> <dl class="dl-horizontal"> <dt>Neck Width</dt> <dd> <div id="funnelNeckWidth"></div> </dd> </dl> <dl class="dl-horizontal"> <dt>Neck Height</dt> <dd> <div id="funnelNeckHeight"></div> </dd> </dl> <dl class="dl-horizontal"> <dt></dt> <dd> <select id="funnelType"> <option value="default" selected="selected">Default</option> <option value="rectangle">Rectangle</option> </select> </dd> </dl>
// create FlexChart and Menus var funnelChart = new wijmo.chart.FlexChart('#funnelChart'), neckWidth = new wijmo.input.InputNumber('#funnelNeckWidth'), funnelType = new wijmo.input.Menu('#funnelType'), neckHeight = new wijmo.input.InputNumber('#funnelNeckHeight'); // initialize FlexChart's properties funnelChart.initialize({ itemsSource: funnelData, chartType: wijmo.chart.ChartType.Funnel, bindingX: 'country', series: [ { name: 'Sales', binding: 'sales' } ], dataLabel: { content: '{y}' }, options: { funnel: { neckWidth: 0.2, neckHeight: 0.2, type: 'default' } } }); // neckWidth - initialize InputNumber's properties neckWidth.min = 0; neckWidth.max = 1; neckWidth.step = 0.1; neckWidth.valueChanged.addHandler(function (sender) { if (sender.value < sender.min || sender.value > sender.max) { return; } funnelChart.options.funnel.neckWidth = sender.value; funnelChart.refresh(true); }); neckWidth.value = 0.2; // neckHeight - initialize InputNumber's properties neckHeight.min = 0; neckHeight.max = 1; neckHeight.step = 0.1; neckHeight.valueChanged.addHandler(function (sender) { if (sender.value < sender.min || sender.value > sender.max) { return; } funnelChart.options.funnel.neckHeight = sender.value; funnelChart.refresh(true); }); neckHeight.value = 0.2; updateMenuHeader(funnelType, 'Funnel Type'); funnelType.selectedIndexChanged.addHandler(function () { if (funnelType.selectedValue) { funnelChart.options.funnel.type = funnelType.selectedValue; updateMenuHeader(funnelType, 'Funnel Type'); funnelChart.refresh(true); } }); // helper function for Menu headers function updateMenuHeader(menu, prefix) { menu.header = '' + prefix + ': ' + menu.text; }

结果:

Neck Width
Neck Height

混合图表类型

你可以对每个图表系列使用不同的图表类型,这是通过对它这个系列本身设置chartType属性。 这会覆盖图表的默认图表类型。

在以下的示例,这个图表的chartType属性被设为Column, 但是Downloads系列使用了LineAndSymbol类型覆盖它:

<div id="mixedTypesChart"></div>
// create FlexChart var mixedTypesChart = new wijmo.chart.FlexChart('#mixedTypesChart'); // initialize FlexChart's properties mixedTypesChart.initialize({ itemsSource: appData, bindingX: 'country', series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads', chartType: wijmo.chart.ChartType.LineSymbols } ] });

结果:

图例和标题

使用legend属性来自定义图表图例的外观, and 使用headerfooter和坐标的title属性来向你的图表添加标题。

你可以使用CSS来确定图例和标题的样式。下面的CSS标签显示用于自定义图例和标题的外观的规则。 注意它们是SVG元素,所以你必须使用”fill”这样的CSS属性而不是”color”。

<div id="chartLegendTitles"></div> <dl class="dl-horizontal"> <dt>Header</dt><dd><input id="headerInput" class="form-control"/></dd> <dt>Footer</dt><dd><input id="footerInput" class="form-control"/></dd> <dt>X-Axis Title</dt><dd><input id="xTitleInput" class="form-control"/></dd> <dt>Y-Axis Title</dt><dd><input id="yTitleInput" class="form-control"/></dd> <dt></dt> <dd> <select id="positionMenu"> <option value="0">None</option> <option value="1">Left</option> <option value="2">Top</option> <option value="3" selected="selected">Right</option> <option value="4">Bottom</option> </select> </dd> </dl>
var chartLegendAndTitles = new wijmo.chart.FlexChart('#chartLegendAndTitles'), positionMenu = new wijmo.input.Menu('#positionMenu'), headerInput = document.getElementById('headerInput'), footerInput = document.getElementById('footerInput'), xTitleInput = document.getElementById('xTitleInput'), yTitleInput = document.getElementById('yTitleInput'); // initialize FlexChart's properties chartLegendAndTitles.initialize({ itemsSource: appData, bindingX: 'country', header: 'Sample Chart', footer: 'copyright (c) ComponentOne', axisX: { title: 'country' }, axisY: { title: 'amount' }, series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads' } ] }); // sync the input's value with FlexChart's header headerInput.value = chartLegendAndTitles.header; // update the FlexChart's header headerInput.addEventListener('input', function () { chartLegendAndTitles.header = this.value; }); // sync the input's value with FlexChart's footer footerInput.value = chartLegendAndTitles.footer; // update the FlexChart's footer footerInput.addEventListener('input', function () { chartLegendAndTitles.footer = this.value; }); // sync the input's value with FlexChart's X-Axis title xTitleInput.value = chartLegendAndTitles.axisX.title; // update the FlexChart's X-Axis title xTitleInput.addEventListener('input', function () { chartLegendAndTitles.axisX.title = this.value; }); // sync the input's value with FlexChart's Y-Axis title yTitleInput.value = chartLegendAndTitles.axisY.title; // update the FlexChart's Y-Axis title yTitleInput.addEventListener('input', function () { chartLegendAndTitles.axisY.title = this.value; }); // update menu's header updatePositionMenuHeader(); positionMenu.selectedIndexChanged.addHandler(function () { if (positionMenu.selectedValue) { // update the FlexChart legend's position chartLegendAndTitles.legend.position = parseInt(positionMenu.selectedValue); // update menu's header updatePositionMenuHeader(); } }); function updatePositionMenuHeader() { positionMenu.header = '<b>Legend:</b> ' + positionMenu.text; }
.wj-flexchart .wj-title { font-weight: bold; } .wj-flexchart .wj-header .wj-title { fill: #80044d; font-size: 18pt; } .wj-flexchart .wj-footer .wj-title { fill: #80044d; } .wj-flexchart .wj-axis-x .wj-title, .wj-flexchart .wj-axis-y .wj-title { font-style: italic; }

结果:

页眉
页尾
X轴标题
Y轴标题

工具提示

FlexChart对工具提示有内置的支持。 默认情况下,当用户触摸或者悬停鼠标到一个数据点时,控件会显示工具提示。

工具提示的内容是使用一个可能包含下列参数的模板生成:

默认情况下,tooltip模板被设为<b>{seriesName}</b><br/>{x} {y},你可以在上面的图表看到它是如何工作的。 在这个示例中,我们设tooltip模板为<b>{seriesName}</b> <img src='resources/{x}.png'/><br/>{y}, 它使用国家的国旗代替了国家的名字。

你可以通过设置模板为空字符串来禁用图表tooltips。

<div id="chartTooltip"></div>
// create FlexChart var chartTooltip = new wijmo.chart.FlexChart('#chartTooltip'); // initialize FlexChart's properties chartTooltip.initialize({ itemsSource: appData, bindingX: 'country', tooltip: { content: "<img src='resources/{x}.png' /> <b>{seriesName}</b><br />{y}" }, series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads' } ] });

结果:

样式系列

FlexChart为每个基于默认调色板的系列自动选取颜色,你可以通过设置palette属性来重写它。 但你也可以重写默认的属性,通过设置任意一个系列的style属性为一个对象, 它制定了SVG样式属性,包括fill, stroke, strokeThickness等等。

Series.style属性对在Wijmo中通过CSS设置样式的一般规则来说,是一个例外。 这个例外反映一个事实,许多图表有动态系列,这是不可能提前布置样式的。 比如,一个股票图表可能会展示用户在运行程序时才选中的系列。

这个示例中的图表使用了stylesymbolStyle属性来为每个系列选择样式属性:

<div id="chartSeriesStyle"></div>
// create FlexChart and variables for its series var chartSeriesStyle = new wijmo.chart.FlexChart('#chartSeriesStyle'), salesSeries, expensesSeries, downloadsSeries; chartSeriesStyle.itemsSource = appData; chartSeriesStyle.bindingX = 'country'; // initialize "Sales" data series salesSeries = new wijmo.chart.Series(); salesSeries.name = 'Sales'; salesSeries.binding = 'sales'; salesSeries.style = {}; salesSeries.style.fill = 'green'; salesSeries.style.stroke = 'darkgreen'; salesSeries.style.strokeWidth = 1; // initialize "Expenses" data series expensesSeries = new wijmo.chart.Series(); expensesSeries.name = 'Expenses'; expensesSeries.binding = 'expenses'; expensesSeries.style = {}; expensesSeries.style.fill = 'red'; expensesSeries.style.stroke = 'darkred'; expensesSeries.style.strokeWidth = 1; // initialize "Downloads" data series downloadsSeries = new wijmo.chart.Series(); downloadsSeries.name = 'Downloads'; downloadsSeries.binding = 'downloads'; downloadsSeries.chartType = wijmo.chart.ChartType.LineSymbols; downloadsSeries.style = {}; downloadsSeries.symbolStyle = {}; downloadsSeries.style.stroke = 'orange'; downloadsSeries.style.strokeWidth = 5; downloadsSeries.symbolStyle.fill = 'gold'; downloadsSeries.symbolStyle.stroke = 'gold'; // add data series to chart chartSeriesStyle.series.push(salesSeries); chartSeriesStyle.series.push(expensesSeries); chartSeriesStyle.series.push(downloadsSeries);

结果:

自定义轴

使用axis属性来自定义图表的坐标轴,包括范围(最小值和最大值),便签格式,刻度间隔和网格线。

Axis类有布尔属性,允许你打开或关闭功能(如axisLine, labels, majorTickMarksmajorGrid)。 你可以使用CSS来设置这些已经打开的功能的样式。

<div id="chartCustomizeAxes"></div>
// create FlexChart var chartCustomizeAxes = new wijmo.chart.FlexChart('#chartCustomizeAxes'); // initialize FlexChart's properties chartCustomizeAxes.initialize({ itemsSource: appData, bindingX: 'country', axisX: { axisLine: true, majorGrid: true }, axisY: { format: 'c0', max: 10000, majorUnit: 2000, axisLine: true, majorGrid: true }, series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' } ] });

结果:

主题

FlexChart的外观是在CSS中定义的。除了默认的主题,我们有十几个专业设计的主题。 它们定制了所有Wijmo控件的外观来达到一致的,有吸引力的效果。

为了自定义图表的外观,检查你想要提供样式的元素并创建一下CSS规则来应用到这些元素中。

例如,如果你在IE或者谷歌浏览器上右击X轴上的一个标签,你会发现它是一个拥有”wj-label”类的元素, 它被包含在拥有”wj-flexchart”类的顶层控件元素中。这个示例中第一条CSS规则使用这条信息来自定义X标签。 规则选择器添加了额外的要求,父类元素必须拥有"wj-flexchart"类"custom-flex-chart"类。 如果没有的话,这个规则会用于这个页面所有的图表。

<div id="chartTheme" class="custom-flex-chart"></div>
// create FlexChart var chartTheme = new wijmo.chart.FlexChart('#chartTheme'); // initialize FlexChart's properties chartTheme.initialize({ itemsSource: appData, bindingX: 'country', series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads' } ] });
/* custom chart theme */ .custom-flex-chart.wj-flexchart .wj-axis-x .wj-label, .custom-flex-chart.wj-flexchart .wj-legend .wj-label { font-family: 'Courier New', Courier, monospace; font-weight: bold; } .custom-flex-chart.wj-flexchart .wj-legend > rect, .custom-flex-chart.wj-flexchart .wj-plot-area > rect { fill: #f8f8f8; stroke: #c0c0c0; }

结果:

选择模式

FlexChart允许你通过单击或者触摸选择系列或数据点。使用selectionMode属性来指定是否允许选择系列, 是否选择数据点或者无法选择(选择默认是关闭的)

设置selectionMode属性为Series或者Point会导致用户在单击鼠标的时候, FlexChart自动更新Selection属性, 并且将"wj-state-selected"类应用到选中的图表元素中。

Selection属性返回当前选中的系列。要得到当前选中的数据点, 得到当前选定的项并在选中的系列中使用Series.collectionView.currentItem属性,正如示例所示。

<div id="chartSelectionMode"></div> <select id="seletionModeMenu"> <option value="0">None</option> <option value="1" selected="selected">Series</option> <option value="2">Point</option> </select> <select id="chartTypeMenu"> <option value="0" selected="selected">Column</option> <option value="1">Bar</option> <option value="2">Scatter</option> <option value="3">Line</option> <option value="4">LineSymbols</option> <option value="5">Area</option> <option value="9">Spline</option> <option value="10">SplineSymbols</option> <option value="11">SplineArea</option> </select> <div id="seriesContainer" style="display:none"> <h4>Current Selection</h4> <p>Series: <b id="seriesName"></b></p> <dl id="detailContainer" class="dl-horizontal" style="display:none"> <dt>Country</dt><dd id="seriesCountry"></dd> <dt>Sales</dt><dd id="seriesSales"></dd> <dt>Expenses</dt><dd id="seriesExpenses"></dd> <dt>Downloads</dt><dd id="seriesDownloads"></dd> </dl> </div>
var chartSelectionMode = new wijmo.chart.FlexChart('#chartSelectionMode'), typeMenu = new wijmo.input.Menu('#chartTypeMenu'), selectionModeMenu = new wijmo.input.Menu('#seletionModeMenu'), seriesContainer = document.getElementById('seriesContainer'), detailContainer = document.getElementById('detailContainer'); // initialize FlexChart's properties chartSelectionMode.initialize({ itemsSource: appData, bindingX: 'country', selectionMode: wijmo.chart.SelectionMode.Series, series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads' } ] }); // update details when the FlexChart's selection changes chartSelectionMode.selectionChanged.addHandler(function () { var currentSelection = chartSelectionMode.selection, currentSelectItem; if (currentSelection) { seriesContainer.style.display = 'block'; // show container document.getElementById('seriesName').innerHTML = currentSelection.name; currentSelectItem = currentSelection.collectionView.currentItem; if (currentSelectItem && selectionModeMenu.selectedValue === '2') { setSeriesDetail(currentSelectItem); // update details } } }); // update Menu header updateMenuHeader(typeMenu, 'Chart Type'); typeMenu.selectedIndexChanged.addHandler(function () { if (typeMenu.selectedValue) { // update FlexChart' chartType chartSelectionMode.chartType = parseInt(typeMenu.selectedValue); // update Menu header updateMenuHeader(typeMenu, 'Chart Type'); } }); // update Menu header updateMenuHeader(selectionModeMenu, 'Selection Mode'); selectionModeMenu.selectedIndexChanged.addHandler(function () { if (selectionModeMenu.selectedValue) { // update FlexChart' selectionMode chartSelectionMode.selectionMode = parseInt(selectionModeMenu.selectedValue); // toggle the series panel's visiblity if (selectionModeMenu.selectedValue === '0' || !chartSelectionMode.selection) { seriesContainer.style.display = 'none'; } else { seriesContainer.style.display = 'block'; } // toggle the series panel's visiblity if (selectionModeMenu.selectedValue !== '2' || !chartSelectionMode.selection || !chartSelectionMode.selection.collectionView.currentItem) { detailContainer.style.display = 'none'; } else { // update the details setSeriesDetail(chartSelectionMode.selection.collectionView.currentItem); } // update Menu header updateMenuHeader(selectionModeMenu, 'Selection Mode'); } }); // helper method to show details of the FlexChart's current selection function setSeriesDetail(currentSelectItem) { detailContainer.style.display = 'block'; document.getElementById('seriesCountry').innerHTML = currentSelectItem.country; document.getElementById('seriesSales').innerHTML = wijmo.Globalize.format(currentSelectItem.sales, 'c2'); document.getElementById('seriesExpenses').innerHTML = wijmo.Globalize.format(currentSelectItem.expenses, 'c2'); document.getElementById('seriesDownloads').innerHTML = wijmo.Globalize.format(currentSelectItem.downloads, 'n0'); }; // helper method for changing menu header function updateMenuHeader(menu, prefix) { menu.header = '<b>' + prefix + '</b>: ' + menu.text; }

结果:

切换系列

Series类有一个visibility属性,让你决定一个系列是否应该展现在图表和图例中, 或者只在图例中,或者完全隐藏。

这个示例演示你应该如何使用visibility属性来通过两种方法切换系列的可见性:

  1. 单击图例入口:
    图表会设置图表的option.legendToggle属性为true, 当它的图例入口被单击的时候就会切换一个系列的visibility属性。
  2. 使用checkbox:
    checked状态改变后,它会通过checked状态设置每个系列的checked属性。
<div id="chartLegendToggle"></div> Sales <input id="cbSales" type="checkbox"/><br /> Expenses <input id="cbExpenses" type="checkbox"/><br /> Downloads <input id="cbDownloads" type="checkbox"/>
// create FlexChart var chartLegendToggle = new wijmo.chart.FlexChart('#chartLegendToggle'); // initialize FlexChart's properties chartLegendToggle.initialize({ itemsSource: appData, bindingX: 'country', legendToggle: true, series: [ { name: 'Sales', binding: 'sales' }, { name: 'Expenses', binding: 'expenses' }, { name: 'Downloads', binding: 'downloads' } ] }); chartLegendToggle.seriesVisibilityChanged.addHandler(function () { // loop through chart series chartLegendToggle.series.forEach(function (series) { var seriesName = series.name, checked = series.visibility === wijmo.chart.SeriesVisibility.Visible; // update custom checkbox panel document.getElementById('cb' + seriesName).checked = checked; }); }); // loop through custom check boxes ['cbSales', 'cbExpenses', 'cbDownloads'].forEach(function (item, index) { // update checkbox and toggle FlexChart's series visibility when clicked var el = document.getElementById(item); el.checked = chartLegendToggle.series[index].visibility === wijmo.chart.SeriesVisibility.Visible; el.addEventListener('click', function () { if (this.checked) { chartLegendToggle.series[index].visibility = wijmo.chart.SeriesVisibility.Visible; } else { chartLegendToggle.series[index].visibility = wijmo.chart.SeriesVisibility.Legend; } }); });

结果:

Sales
Expenses
Downloads

渐变色

FlexChart支持渐变色。

渐变描述符是如下格式的表达式: <type>(<coords>)<colors>[:<offset>[:<opacity>]][-<colors>[:<offset>[:<opacity>]]]-<colors>[:<offset>[:<opacity>]]. <type>可以是线性的,也可以是径向的。 大写L或者R字母表示从SVG表明偏移的绝对坐标。 小写l或者r字母表示相对于应用渐变的元素计算的坐标。 坐标指定一个线性渐变向量x1, y1, x2, y2, 或者径向渐变向量 cx, cy, r和可选fx, fy, fr 指定远离圆心的焦点。 将<colors>指定为以虚线分隔的CSS颜色值的列表。 每种颜色可以后跟一个自定义偏移和不透明度值,用冒号字符分隔。

线性渐变格式示例:

'l(0,0,1,0)#ff0000-#00ff00-#0000ff', 'L(0,0,300,300)#ff0000:0.2:0.2-00ff00:0.8'

径向渐变格式示例:

'r(0.5,0.5,1)#ff0000-#0000ff', 'R(100,100,100,200,200,200)#ff0000-#0000ff'

基本

从预定义的渐变颜色中选择以查看不同的外观。

<div id="predefinedChart"></div> <div> <select id="predefinedColorMenu"> <option value="l(0,0,1,0)#89f7fe-#66a6ff" selected="selected">Light Blue - l(0, 0, 1, 0)#89f7fe-#66a6ff</option> <option value="l(0,0,0,1)#13547a-#80d0c7">Aqua - l(0, 0, 0, 1)#13547a-#80d0c7</option> <option value="l(0,0,1,1)#ff0844-#ffb199">Red - l(0, 0, 1, 1)#ff0844-#ffb199</option> <option value="l(0,0,1,0)#b224ef-#7579ff-#b224ef">Purple - l(0, 0, 1, 0)#b224ef-#7579ff-#b224ef</option> <option value="r(0.5,0.5,0.7)#cc208e-#6713d2">Plum - r(0.5,0.5,0.7)#cc208e-#6713d2</option> <option value="l(0,0,1,0)#30cfd0-#330867">Deep Blue - l(0, 0, 1, 0)#30cfd0-#330867</option> <option value="l(0,0,0,1)#e27f00-#ae1a73">Orange - l(0, 0, 0, 1)#e27f00-#ae1a73</option> <option value="l(0,0,1,1)#abd800-#5c7e00">Green - l(0, 0, 1, 1)#abd800-#5c7e00</option> </select> </div>
var predefinedChart = new wijmo.chart.FlexChart('#predefinedChart'), predefinedColorMenu = new wijmo.input.Menu('#predefinedColorMenu'); // initialize FlexChart's properties predefinedChart.initialize({ itemsSource: appData, bindingX: 'country', series: [ { binding: 'sales' } ] }); updateMenuHeader(predefinedColorMenu, 'Color'); predefinedColorMenu.selectedIndexChanged.addHandler(function () { if (predefinedColorMenu.selectedValue) { applyBasicGradientColor(); updateMenuHeader(predefinedColorMenu, 'Color'); } }); applyBasicGradientColor(); function applyBasicGradientColor() { predefinedChart.series[0].style = { fill: predefinedColorMenu.selectedValue }; predefinedChart.refresh(true); }

结果:

高级

设置多个选项来自定义渐变色。

<div id="chartGradientColors"></div> <dl class="dl-horizontal"> <dt>Generated fill string:</dt> <dd> <label id="gradientColorsLabel"></label> </dd> <dt></dt> <dd> <select id="gradientChartType"> <option value="0" selected="selected">Column</option> <option value="1">Bar</option> <option value="5">Area</option> <option value="11">SplineArea</option> </select> </dd> <dt></dt> <dd> <select id="gradientTypeMenu"> <option value="l" selected="selected">Linear</option> <option value="r">Radial</option> </select> </dd> <dt id="dtGradientDirection"></dt> <dd id="ddGradientDirection"> <select id="gradientDirectionMenu"> <option value="horizontal" selected="selected">Horizontal</option> <option value="vertical">Vertical</option> </select> </dd> <dt>Start Color:</dt> <dd><input id="gradientStartColor"/></dd> <dt>Start Offset:</dt> <dd><input id="gradientStartOffset"/></dd> <dt>Start Opacity:</dt> <dd><input id="gradientStartOpacity"/></dd> <dt>End Color:</dt> <dd><input id="gradientEndColor"/></dd> <dt>End Offset:</dt> <dd><input id="gradientEndOffset"/></dd> <dt>End Opacity:</dt> <dd><input id="gradientEndOpacity"/></dd> </dl>
// create FlexChart and Menus var chart = new wijmo.chart.FlexChart('#chartGradientColors'), gredientLabel = document.getElementById('gradientColorsLabel'), gradientChartType = new wijmo.input.Menu('#gradientChartType'), type = new wijmo.input.Menu('#gradientTypeMenu'), dtDirection = document.getElementById('dtGradientDirection'), ddDirection = document.getElementById('ddGradientDirection'), direction = new wijmo.input.Menu('#gradientDirectionMenu'), startColor = new wijmo.input.InputColor('#gradientStartColor'), startOffset = new wijmo.input.InputNumber('#gradientStartOffset'), startOpacity = new wijmo.input.InputNumber('#gradientStartOpacity'), endColor = new wijmo.input.InputColor('#gradientEndColor'), endOffset = new wijmo.input.InputNumber('#gradientEndOffset'), endOpacity = new wijmo.input.InputNumber('#gradientEndOpacity'); // initialize FlexChart's properties chart.initialize({ itemsSource: appData, bindingX: 'country', series: [ { binding: 'sales' } ] }); applyGradientColor(); //chart type - initialize Menu's properties updateMenuHeader(gradientChartType, 'Chart Type'); gradientChartType.selectedIndexChanged.addHandler(function () { if (gradientChartType.selectedValue) { chart.chartType = +gradientChartType.selectedValue; updateMenuHeader(gradientChartType, 'Chart Type'); } }); //startColor - initialize InputColor's properties startColor.valueChanged.addHandler(function (sender) { applyGradientColor(); }); startColor.value = '#ff0000'; // startOffset - initialize InputNumber's properties startOffset.min = 0; startOffset.max = 1; startOffset.step = 0.1; startOffset.valueChanged.addHandler(function (sender) { if (sender.value < sender.min || sender.value > sender.max) { return; } applyGradientColor(); }); startOffset.value = 0; // startOpacity - initialize InputNumber's properties startOpacity.min = 0; startOpacity.max = 1; startOpacity.step = 0.1; startOpacity.valueChanged.addHandler(function (sender) { if (sender.value < sender.min || sender.value > sender.max) { return; } applyGradientColor(); }); startOpacity.value = 1; //endColor - initialize InputColor's properties endColor.valueChanged.addHandler(function (sender) { applyGradientColor(); }); endColor.value = '#0000ff'; // endOffset - initialize InputNumber's properties endOffset.min = 0; endOffset.max = 1; endOffset.step = 0.1; endOffset.valueChanged.addHandler(function (sender) { if (sender.value < sender.min || sender.value > sender.max) { return; } applyGradientColor(); }); endOffset.value = 1; // endOpacity - initialize InputNumber's properties endOpacity.min = 0; endOpacity.max = 1; endOpacity.step = 0.1; endOpacity.valueChanged.addHandler(function (sender) { if (sender.value < sender.min || sender.value > sender.max) { return; } applyGradientColor(); }); endOpacity.value = 1; updateMenuHeader(type, 'Type'); type.selectedIndexChanged.addHandler(function () { if (type.selectedValue) { updateMenuHeader(type, 'Type'); applyGradientColor(); } }); updateMenuHeader(direction, 'Direction'); direction.selectedIndexChanged.addHandler(function () { if (direction.selectedValue) { updateMenuHeader(direction, 'Direction'); applyGradientColor(); } }); // helper function for Menu headers function updateMenuHeader(menu, prefix) { menu.header = '' + prefix + ': ' + menu.text; } function applyGradientColor() { var color = '', t = type.selectedValue, d = direction.selectedValue; color = t; if (t === 'l') { dtDirection.style.display = 'block'; ddDirection.style.display = 'block'; if (d === 'horizontal') { color += '(0, 0, 1, 0)'; } else { color += '(0, 0, 0, 1)'; } } else { dtDirection.style.display = 'none'; ddDirection.style.display = 'none'; color += '(0.5, 0.5, 0.5)' } color += startColor.value; if (startOffset.value !== 0 || startOpacity.value !== 1) { color += ':' + startOffset.value; } if (startOpacity.value !== 1) { color += ':' + startOpacity.value; } color += '-' + endColor.value; if (endOffset.value !== 1 || endOpacity.value !== 1) { color += ':' + endOffset.value; } if (endOpacity.value !== 1) { color += ':' + endOpacity.value; } gradientColorsLabel.innerHTML = color; chart.series[0].style = { fill: color }; chart.refresh(true); }

结果:

生成填充字符串:
Start Color:
Start Offset:
Start Opacity:
End Color:
End Offset:
End Opacity:

动态图表

FlexChart内部使用了ICollectionView,因此你对数据源做的任何更改都会自动反映在图表中。

在这个示例中,我们使用一个计时器来向数据源中增加项目,丢弃旧项目以保持总数为200。 结果就是一个动态的图表,当新数据到来时图表向右滚动。

<div id="dynamicChart"></div> <dl class="dl-horizontal"> <dt>Update Speed</dt> <dd> <div class="btn-group"> <button id="btnSlow" type="button" class="btn btn-default">Slow</button> <button id="btnMedium" type="button" class="btn btn-default">Medium</button> <button id="btnFast" type="button" class="btn btn-default">Fast</button> <button id="btnStop" type="button" class="btn btn-default">Stop</button> </div> </dd> </dl>
// dynamic data var toAddData, interval, trafficData = new wijmo.collections.ObservableArray(), setInterval = function (interval) { if (toAddData) { clearTimeout(toAddData); toAddData = null; } if (interval) { toAddData = setTimeout(function () { addTrafficItem(trafficData, interval); }); } }, // define the interval hash for the speed buttons intervalHash = { Slow: 200, Medium: 100, Fast: 50, Stop: 0 }, // create FlexChart dynamicChart = new wijmo.chart.FlexChart('#dynamicChart'); // initialize FlexChart's properties dynamicChart.initialize({ chartType: wijmo.chart.ChartType.Area, stacking: wijmo.chart.Stacking.Stacked, itemsSource: trafficData, bindingX: 'time', axisX: { format: 'mm:ss' }, series: [ { name: 'Trucks', binding: 'trucks' }, { name: 'Ships', binding: 'ships' }, { name: 'Planes', binding: 'planes' } ] }); setInterval(500); // Bind the click event to the speed buttons for (var prop in intervalHash) { document.getElementById('btn' + prop).addEventListener('click', buttonClick(intervalHash[prop])); } function buttonClick(value) { return function () { setInterval(value); }; } function addTrafficItem(trafficData, interval) { var len = trafficData.length, last = len ? trafficData[len - 1] : null, trucks = last ? last.trucks : 0, ships = last ? last.ships : 0, planes = last ? last.planes : 0; trucks = Math.max(0, trucks + Math.round(Math.random() * 50 - 25)); ships = Math.max(0, ships + Math.round(Math.random() * 10 - 5)); planes = Math.max(0, planes + Math.round(Math.random() * 10 - 5)); // add random data, limit array length trafficData.push({ time: new Date(), trucks: trucks, ships: ships, planes: planes }); if (trafficData.length > 200) { trafficData.splice(0, 1); } // keep adding if (interval) { toAddData = setTimeout(function () { addTrafficItem(trafficData, interval); }, interval); } }

结果:

更新速度