原創(chuàng)|行業(yè)資訊|編輯:何家巧|2023-01-05 16:58:45.633|閱讀 177 次
概述:本文將帶來如何使用 LightningChart 創(chuàng)建 JavaScript HTML可視化動(dòng)圖,我們主要通過六部分進(jìn)行講解,分別是帶有 JavaScript 的 HTML 圖表、項(xiàng)目概況、配置模板、條形圖、環(huán)形圖、游標(biāo)圖表、使用 JavaScript 的 HTML 圖表,希望為您的開發(fā)帶來幫助。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
LightningChart JS是一款高性能的JavaScript圖標(biāo)庫,專注于實(shí)時(shí)數(shù)據(jù)可視化,以“快如閃電”享譽(yù)全球,是Microsoft Visual Studio數(shù)據(jù)展示速度最快的2D和3D圖表制圖組件,可實(shí)時(shí)呈現(xiàn)超過10億數(shù)據(jù)點(diǎn)的海量數(shù)據(jù)。
本文將帶來如何使用 LightningChart 創(chuàng)建 JavaScript HTML可視化動(dòng)圖,我們主要通過六部分進(jìn)行講解,分別是帶有 JavaScript 的 HTML 圖表、項(xiàng)目概況、配置模板、條形圖、環(huán)形圖、游標(biāo)圖表、使用 JavaScript 的 HTML 圖表,希望為您的開發(fā)帶來幫助。
帶有 JavaScript 的 HTML 圖表
制作HTML圖表對(duì)于各個(gè)級(jí)別的開發(fā)工作者來說可以輕松實(shí)現(xiàn),但基礎(chǔ)的HTML 5圖表功能和性能有限,特別是在數(shù)據(jù)點(diǎn)的數(shù)量或渲染性能方面。配置模板
const {
lightningChart,
emptyLine,
AutoCursorModes,
UIOrigins,
LegendBoxBuilders,
AxisScrollStrategies,
AxisTickStrategies,
UIElementBuilders,
Themes
} = lcjs
const lc = lightningChart()
IIFE 文件(立即調(diào)用函數(shù)表達(dá)式)包含創(chuàng)建圖表所需的所有 Lightning Chart 函數(shù)和屬性。導(dǎo)入此文件,我們將能夠提取每個(gè)圖表所需的部分:
const {
lightningChart,
emptyLine,
AutoCursorModes,
UIOrigins,
LegendBoxBuilders,
AxisScrollStrategies,
AxisTickStrategies,
UIElementBuilders,
Themes
} = lcjs
const lc = lightningChart()
現(xiàn)在我們必須為條形圖構(gòu)建一個(gè)界面。該界面將包含該圖表的所有屬性。
let barChart
{
barChart = (options) => {
const figureThickness = 10
const figureGap = figureThickness * .25
const groupGap = figureGap * 3.0
const groups = []
const categories = []
在上圖中,我們指定了所有垂直條的大小。對(duì)于此圖表,坐標(biāo)軸和圖表對(duì)象是必需的。在圖表對(duì)象中,我們將指定全局屬性,如標(biāo)題、頁面填充和鼠標(biāo)行為。
const chart = lc.ChartXY(options)
.setTitle('Grouped Bars (Employee Count)')
.setAutoCursorMode(AutoCursorModes.onHover)
// Disable mouse interactions (e.g. zooming and panning) of plotting area
.setMouseInteractions(false)
// Temporary fix for library-side bug. Remove after fixed.
.setPadding({ bottom: 30 })
// X-axis of the series
const axisX = chart.getDefaultAxisX()
.setMouseInteractions(false)
.setScrollStrategy(undefined)
// Disable default ticks.
.setTickStrategy(AxisTickStrategies.Empty)
// Y-axis of the series
const axisY = chart.getDefaultAxisY()
.setMouseInteractions(false)
.setTitle('Number of Employees')
.setInterval(0, 70)
.setScrollStrategy(AxisScrollStrategies.fitting)
要?jiǎng)?chuàng)建引用特定軸的對(duì)象,我們將使用函數(shù)[getDefaultAxisX -Y]并添加一些其他屬性。[ setAutoCursor]函數(shù)可以讓我們修改光標(biāo)在圖表上的視覺屬性。
chart.setAutoCursor(cursor => cursor
.disposePointMarker()
.disposeTickMarkerX()
.disposeTickMarkerY()
.setGridStrokeXStyle(emptyLine)
.setGridStrokeYStyle(emptyLine)
.setResultTable((table) => {
table
.setOrigin(UIOrigins.CenterBottom)
})
)
emptyLine 屬性將隱藏線指示器:
以下函數(shù)創(chuàng)建了一個(gè)矩形系列(針對(duì)每個(gè)類別),它向其中添加了游標(biāo)功能。
const createSeriesForCategory = (category) => {
const series = chart.addRectangleSeries()
// Change how marker displays its information.
series.setCursorResultTableFormatter((builder, series, figure) => {
// Find cached entry for the figure.
let entry = {
name: category.name,
value: category.data[category.figures.indexOf(figure)]
}
// Parse result table content from values of 'entry'.
return builder
.addRow('Department:', entry.name)
.addRow('# of employees:', String(entry.value))
})
return series
}
在前面的函數(shù)中,我們添加了部門名稱和員工人數(shù)。這些值現(xiàn)在將作為垂直線內(nèi)的行數(shù)據(jù)添加。在以下屬性中,我們可以將這些值的行為指定為“圖例框”。
const legendBox = chart.addLegendBox(LegendBoxBuilders.VerticalLegendBox)
.setAutoDispose({
type: 'max-width',
maxWidth: 0.20,
})
.setTitle('Department')
以下函數(shù)根據(jù)組和類別的值重新繪制條形圖:
const redraw = () => {
let x = 0
for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
const group = groups[groupIndex]
const xStart = x
for (const category of categories) {
const value = category.data[groupIndex]
if (value !== undefined) {
// Position figure of respective value.
const figure = category.figures[groupIndex]
figure.setDimensions({
x,
y: 0,
width: figureThickness,
height: value
})
// Figure gap
x += figureThickness + figureGap
}
}
// Position CustomTick
group.tick.setValue((xStart + x - figureGap) / 2)
// Group gap
x += groupGap
}
axisX.setInterval(-(groupGap + figureGap), x)
}
我們必須添加組和類別。對(duì)于每個(gè)類別,我們將使用重繪函數(shù)繪制一個(gè)條形圖。最后,barChart 對(duì)象將提供類別和組。
const addGroups = (names) => {
for (const name of names)
groups.push({
name,
tick: axisX.addCustomTick(UIElementBuilders.AxisTick)
.setGridStrokeLength(0)
.setTextFormatter((_) => name)
})
}
const addCategory = (entry) => {
// Each category has its own series.
const series = createSeriesForCategory(entry)
.setName(entry.name)
entry.figures = entry.data.map((value) => series.add({ x: 0, y: 0, width: 0, height: 0 }))
legendBox.add(series)
categories.push(entry)
redraw()
}
// Return public methods of a bar chart interface.
return {
addCategory,
addGroups
}
最后,我們可以為圖表指定主題 (UI),并將類別和數(shù)據(jù)添加到該對(duì)象。
const chart = barChart({
theme: Themes.darkGreen,
})
// Add groups
chart.addGroups(['Finland', 'Germany', 'UK'])
// Add categories of bars
const categories = ['Engineers', 'Sales', 'Marketing']
const data = [ [50, 27, 24],
[19, 40, 14],
[33, 33, 62]
]
data.forEach((data, i) => chart.addCategory({
name: categories[i],
data
})
)
環(huán)形圖
現(xiàn)在,我們需要?jiǎng)?chuàng)建一個(gè)包含此類圖表所有屬性的對(duì)象。在這種情況下,我們將創(chuàng)建 [donut] 對(duì)象。我們可以添加主題和類型圖表屬性。
const donut = lightningChart().Pie({
theme: Themes.darkGold,
type: PieChartTypes.LabelsInsideSlices
})
.setTitle('Inter Hotels - hotel visitors in June 2016')
.setPadding({ top: 40 })
.setAnimationsEnabled(true)
.setMultipleSliceExplosion(false)
// Style as "Donut Chart"
.setInnerRadius(60)
// ----- Static data -----
const data = {
country: ['US', 'Canada', 'Greece', 'UK', 'Finland', 'Denmark'],
values: [15000, 20030, 8237, 16790, 9842, 4300]
}
[data] 對(duì)象將是一個(gè) JSON 對(duì)象,其中包含要在此圖表上顯示的數(shù)據(jù)。這個(gè) JSON 可以從另一個(gè)文件導(dǎo)入,對(duì)于這個(gè)例子,我直接在嵌入式代碼中創(chuàng)建了 JSON 對(duì)象。
在下面的函數(shù)中,我們將映射數(shù)組對(duì)象中的所有 JSON 成員:
const processedData = []
let totalVisitor = 0
for (let i = 0; i < data.values.length; i++) {
totalVisitor += data.values[i]
processedData.push({ name: `${data.country[i]}`, value: data.values[i] })
}
現(xiàn)在我們可以映射數(shù)組對(duì)象中的所有成員。所有值都將作為新的“切片”添加到甜甜圈中(使用 [addSlice] 函數(shù))。
processedData.map((item) => donut.addSlice(item.name, item.value))
donut.setLabelFormatter(SliceLabelFormatters.NamePlusValue)
// ----- Add LegendBox -----
donut.addLegendBox(LegendBoxBuilders.HorizontalLegendBox)
.setAutoDispose({
type: 'max-width',
maxWidth: 0.80,
})
.add(donut)
[addLegendBox] 函數(shù)將創(chuàng)建一個(gè)框,其中包含甜甜圈中切片的名稱。我們可以將其創(chuàng)建為水平框或垂直框:
為了完成此圖表,我們可以添加具有某些屬性的 HTML 文本。
donut.addUIElement(UIElementBuilders.TextBox)
.setPosition({ x: 50, y: 50 })
.setOrigin(UIOrigins.CenterTop)
.setDraggingMode(UIDraggingModes.notDraggable)
.setMargin(5)
.setTextFont(fontSettings => fontSettings.setSize(25))
.setText(`Total: ${totalVisitor} visitors`)
.setBackground((background) => background
.setFillStyle(emptyFill)
.setStrokeStyle(emptyLine)
)
這有助于顯示匯總數(shù)據(jù):
游標(biāo)圖表
對(duì)于此圖表,我們有以下三個(gè)常量:
// names of the data the series
const names = ["Stock Price A", "Stock Price B", "Stock Price C"];
// define date that matches value of 0 on date time axis.
const dateOrigin = new Date(2020, 0, 1);
// X step between data points.
const dataFrequency = 30 * 24 * 60 * 60 * 1000;
數(shù)組 [names] 將包含三個(gè)類別;每個(gè)類別將對(duì)應(yīng)于圖表中的線條。我們現(xiàn)在將創(chuàng)建圖表對(duì)象。
圖表對(duì)象的類型為 [ChartXY];我們可以添加一些 UI 屬性,例如主題和標(biāo)題。
// Create a XY Chart.
const chart = lightningChart()
.ChartXY({
theme: Themes.darkGold,
})
// Disable native AutoCursor to create custom
.setAutoCursorMode(AutoCursorModes.disabled)
// set title of the chart
.setTitle("Custom Cursor using HTML");
// Configure X axis as date time.
chart
.getDefaultAxisX()
.setTickStrategy(AxisTickStrategies.DateTime, (tickStrategy) =>
tickStrategy.setDateOrigin(dateOrigin)
);
chart.getDefaultAxisY().setTitle("Stock price variation €");
為了填充我們的圖表,我們需要?jiǎng)?chuàng)建一個(gè)系列數(shù)據(jù)。對(duì)于此圖表,我們將提供系列數(shù)組。
數(shù)組的大小是三個(gè),參考圖表中顯示的線條。點(diǎn)數(shù)限制為 20,而 X 軸的值將使用 [dataFrequency] 常量計(jì)算。
const series = new Array(3).fill(0).map((_, i) => {
const nSeries = chart
.addPointLineSeries()
.setMouseInteractions(false)
createProgressiveTraceGenerator()
.setNumberOfPoints(20)
.generate()
.toPromise()
.then((data) => {
return nSeries.setName(names[i]).add(
data.map((point) => ({
x: point.x * dataFrequency,
y: point.y,
}))
);
});
return nSeries;
});
現(xiàn)在我們將文本框添加到數(shù)據(jù)點(diǎn)。基本上,我們創(chuàng)建了一些帶有 id 的 HTML div。這些 div 將使用 id 作為標(biāo)識(shí)符動(dòng)態(tài)修改。
const styleElem = document.head.appendChild(document.createElement("style"));
const textBox = document.createElement("div");
textBox.id = "resultTable";
const line = document.createElement("div");
line.id = "line";
const line2 = document.createElement("div");
line2.id = "line2";
const arrow = document.createElement("div");
arrow.id = "arrow";
textBox.appendChild(line);
textBox.appendChild(line2);
textBox.appendChild(arrow);
chart.engine.container.append(textBox);
您會(huì)找到 [onSeriesBackgroundMouseMove] 函數(shù)。在這里您將能夠修改光標(biāo)行為,例如,添加淡入淡出效果、修改文本框的比例以及向光標(biāo)添加 HTML 屬性。
chart.onSeriesBackgroundMouseMove((_, event) => {
const mouseLocationClient = { x: event.clientX, y: event.clientY };
// Translate mouse location to LCJS coordinate system for solving data points from series, and translating to Axes.
const mouseLocationEngine = chart.engine.clientLocation2Engine(
mouseLocationClient.x,
mouseLocationClient.y
);
// Translate mouse location to Axis.
const mouseLocationAxis = translatePoint(
mouseLocationEngine,
chart.engine.scale,
series[0].scale
);
// Solve nearest data point to the mouse on each series.
const nearestDataPoints = series.map((el) =>
el.solveNearestFromScreen(mouseLocationEngine)
);
最后,我們只需要為我們之前創(chuàng)建的 div 添加 CSS 樣式。我們可以將 CSS 字符串類附加到文檔標(biāo)頭。
function addStyle(styleString) {
const style = document.createElement("style");
style.textContent = styleString;
document.head.append(style);
}
在 addStyle 對(duì)象中,我們將使用我們之前指定的 ID 找到每個(gè) div 的屬性:
addStyle(`
#resultTable {
background-color: rgba(24, 24, 24, 0.9);
color: white;
font-size: 12px;
border: solid white 2px;
border-radius: 5px;
width: 142px;
// height: 110px;
height: auto;
top: 0;
left: 0;
position: fixed;
padding: 0;
pointer-events:none;
z-index: 1;
transition: left 0.2s, top 0.2s, opacity 0.2s;
opacity: 0.0;
}
另一個(gè)優(yōu)點(diǎn)是 LC 可以為我們提供的出色的圖形界面。不用創(chuàng)建復(fù)雜的 JavaScript、JQuery 或 CSS 函數(shù),我們只需使用帶有 JavaScript 的 HTML 圖表,就可以生成與任何 Web 瀏覽器兼容的漂亮圖表。
歡迎加入LightningChart技術(shù)交流群,獲取最新產(chǎn)品咨詢:740060302
想了解Lightning Charts JS 購買/授權(quán)/試用下載,歡迎咨詢。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn