龙空技术网

如何使用LightningChart JS创建高性能可视化的HTML图表?

慧都科技 681

前言:

此刻兄弟们对“好看的html表格样式”可能比较珍视,我们都需要分析一些“好看的html表格样式”的相关内容。那么小编也在网摘上汇集了一些有关“好看的html表格样式””的相关知识,希望小伙伴们能喜欢,兄弟们一起来学习一下吧!

LightningChart JS是一款高性能的JavaScript图标库,专注于实时数据可视化,以“快如闪电”享誉全球,是Microsoft Visual Studio数据展示速度最快的2D和3D图表制图组件,可实时呈现超过10亿数据点的海量数据。

LightningChart JS官方最新版免费下载试用,历史版本下载,在线文档和帮助文件下载-慧都网

本文将带来如何使用 LightningChart 创建 JavaScript HTML可视化动图,我们主要通过六部分进行讲解,分别是带有 JavaScript 的 HTML 图表、项目概况、配置模板、条形图、环形图、游标图表、使用 JavaScript 的 HTML 图表,希望为您的开发带来帮助。

带有 JavaScript 的 HTML 图表

制作HTML图表对于各个级别的开发工作者来说可以轻松实现,但基础的HTML 5图表功能和性能有限,特别是在数据点的数量或渲染性能方面。

今天我们将用一个HTML模板和LightningCharts制作一个具有高性能可视化的HTML图表。其中一些库可以作为嵌入式JavaScript代码使用。

本次我们将创建三个图表。

HTML光标图条形图环形图项目概况

下方视频演示了在运用"lc js"HTML模板时,带有JavaScript的HTML图表是怎样展示的,本个应用程序有三种不同的图表类型。

您可以看到,对于这个特定的项目,您只需要一个 Web 浏览器就可以对该HTML 图表进行可视化,这次我们将创建一些更高级的东西,通过使用LightningChart JS来确保高性能和快速交互式 HTML 图表与 JavaScript 的安全。

配置模板请下载本文中提供的模板。您将看到一个文件树,其中每个 HTML 文件都具有 Head – Style – Body 结构。

在标题部分,我们将指定页面的属性。在这里,我们将为模板指定样式属性 (CSS)。

在正文中,我们将嵌入我们的 JavaScript 代码。对于 HTML,我们将使用 <script> 标签来处理客户端 JavaScript。HTML 模板非常简单,但您可以根据需要对其进行编辑并使其变得更复杂。

注意:与我们之前的文章和教程相反,这次我们不会运行 NPM INSTALL 代码,因为这不是 NodeJS 项目。

条形图

在这三个文件中,我们将看到以下源脚本部分:

const {lightningChart,emptyLine,AutoCursorModes,UIOrigins,LegendBoxBuilders,AxisScrollStrategies,AxisTickStrategies,UIElementBuilders,Themes} = lcjsconst lc = lightningChart()

IIFE 文件(立即调用函数表达式)包含创建图表所需的所有 Lightning Chart 函数和属性。导入此文件,我们将能够提取每个图表所需的部分:

const {lightningChart,emptyLine,AutoCursorModes,UIOrigins,LegendBoxBuilders,AxisScrollStrategies,AxisTickStrategies,UIElementBuilders,Themes} = lcjsconst lc = lightningChart()

现在我们必须为条形图构建一个界面。该界面将包含该图表的所有属性。

let barChart{barChart = (options) => {const figureThickness = 10                const figureGap = figureThickness * .25                const groupGap = figureGap * 3.0                const groups = []const categories = []

在上图中,我们指定了所有垂直条的大小。对于此图表,坐标轴和图表对象是必需的。在图表对象中,我们将指定全局属性,如标题、页面填充和鼠标行为。

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 seriesconst axisX = chart.getDefaultAxisX().setMouseInteractions(false).setScrollStrategy(undefined)// Disable default ticks..setTickStrategy(AxisTickStrategies.Empty)// Y-axis of the seriesconst axisY = chart.getDefaultAxisY().setMouseInteractions(false).setTitle('Number of Employees').setInterval(0, 70).setScrollStrategy(AxisScrollStrategies.fitting)

要创建引用特定轴的对象,我们将使用函数[getDefaultAxisX -Y]并添加一些其他属性。[ setAutoCursor]函数可以让我们修改光标在图表上的视觉属性。

chart.setAutoCursor(cursor => cursor.disposePointMarker().disposeTickMarkerX().disposeTickMarkerY().setGridStrokeXStyle(emptyLine).setGridStrokeYStyle(emptyLine).setResultTable((table) => {table.setOrigin(UIOrigins.CenterBottom)}))

emptyLine 属性将隐藏线指示器:

以下函数创建了一个矩形系列(针对每个类别),它向其中添加了游标功能。

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} 

在前面的函数中,我们添加了部门名称和员工人数。这些值现在将作为垂直线内的行数据添加。在以下属性中,我们可以将这些值的行为指定为“图例框”。

const legendBox = chart.addLegendBox(LegendBoxBuilders.VerticalLegendBox)                      .setAutoDispose({        type: 'max-width',        maxWidth: 0.20,    })    .setTitle('Department') 

以下函数根据组和类别的值重新绘制条形图:

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)}

我们必须添加组和类别。对于每个类别,我们将使用重绘函数绘制一个条形图。最后,barChart 对象将提供类别和组。

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),并将类别和数据添加到该对象。

const chart = barChart({    theme: Themes.darkGreen,})// Add groupschart.addGroups(['Finland', 'Germany', 'UK'])// Add categories of barsconst 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    })) 
环形图

现在,我们需要创建一个包含此类图表所有属性的对象。在这种情况下,我们将创建 [donut] 对象。我们可以添加主题和类型图表属性。

对于 HTML 属性,我们可以设置标题、填充、动画和半径属性:

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] 对象将是一个 JSON 对象,其中包含要在此图表上显示的数据。这个 JSON 可以从另一个文件导入,对于这个例子,我直接在嵌入式代码中创建了 JSON 对象。

在下面的函数中,我们将映射数组对象中的所有 JSON 成员:

const processedData = []let totalVisitor = 0for (let i = 0; i < data.values.length; i++) {    totalVisitor += data.values[i]    processedData.push({ name: `${data.country[i]}`, value: data.values[i] })}

现在我们可以映射数组对象中的所有成员。所有值都将作为新的“切片”添加到甜甜圈中(使用 [addSlice] 函数)。

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] 函数将创建一个框,其中包含甜甜圈中切片的名称。我们可以将其创建为水平框或垂直框:

为了完成此图表,我们可以添加具有某些属性的 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)    )

这有助于显示汇总数据:

游标图表

对于此图表,我们有以下三个常量:

// names of the data the seriesconst 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;

数组 [names] 将包含三个类别;每个类别将对应于图表中的线条。我们现在将创建图表对象。

图表对象的类型为 [ChartXY];我们可以添加一些 UI 属性,例如主题和标题。

要配置轴,我们将使用 [getDefaultAxis] 函数。对于 X 轴,我们将指定计算策略,在本例中为 [DateTime]。我们可以使用 dateOrigin 常量的值来设置起始日期。

// 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 €");

为了填充我们的图表,我们需要创建一个系列数据。对于此图表,我们将提供系列数组。

数组的大小是三个,参考图表中显示的线条。点数限制为 20,而 X 轴的值将使用 [dataFrequency] 常量计算。

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;}); 

现在我们将文本框添加到数据点。基本上,我们创建了一些带有 id 的 HTML div。这些 div 将使用 id 作为标识符动态修改。

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);

您会找到 [onSeriesBackgroundMouseMove] 函数。在这里您将能够修改光标行为,例如,添加淡入淡出效果、修改文本框的比例以及向光标添加 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)  );

最后,我们只需要为我们之前创建的 div 添加 CSS 样式。我们可以将 CSS 字符串类附加到文档标头。

function addStyle(styleString) {  const style = document.createElement("style");  style.textContent = styleString;  document.head.append(style);} 

在 addStyle 对象中,我们将使用我们之前指定的 ID 找到每个 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;    }
使用 JavaScript 制作 HTML 图表

在之前的文章中,我们使用了 Node JS、Electron JS、Quasar JS 以及即将推出的 Android 和 iOS 等技术……但在所有这些中,都需要预先了解这些框架的使用。

并非所有人都能在复杂的 Web 项目上花费大量时间,大部分人可能只是需要一种更专业的方式来展示他们的数据。

本文展示了LightningChart作为简单 HTML 模板中嵌入式代码的灵活性,以及如何使用 JavaScript 轻松创建 HTML 图表。

LightningChart为我们提供了各种示例或模板,使我们能够将代码复制并粘贴到脚本标签中来创建高级图表。

很明显,自定义这些图表可能会很复杂,但是在之前和即将发布的文章中,我们将尝试涵盖所有需求,这样一个简单的 HTML 实现可能就非常简单了。

另一个优点是 LC 可以为我们提供的出色的图形界面。不用创建复杂的 JavaScript、JQuery 或 CSS 函数,我们只需使用带有 JavaScript 的 HTML 图表,就可以生成与任何 Web 浏览器兼容的漂亮图表。

标签: #好看的html表格样式