要在使用 npm 和 webpack 的 React 应用中使用 SciChart.js,建议使用官方的 scichart-react 库。
步骤 1:安装 SciChart.js 和 scichart-react
如果尚未进行,请将 SciChart.js 和 scichart-react 添加到 React 应用中。
npm install scichart
npm install scichart-react
步骤 2:部署 Wasm 文件
SciChart.js 使用 WebAssembly 文件,您需要分发这些文件。最简单的方法是将 wasm 文件从 node_modules/scichart/_wasm 文件夹复制到输出文件夹中。
示例:使用 webpack.config.js 时:
plugins: [
new CopyPlugin({
patterns: [
{ from: "src/index.html", to: "" },
{ from: "node_modules/scichart/_wasm/scichart2d.wasm", to: "" },
// 使用 3D 图表时的选项
{ from: "node_modules/scichart/_wasm/scichart3d.wasm", to: "" },
],
})
],
注:为了简化引入过程, 也可通过CDN加载wasm 或其他方法
步骤3:创建图表
随后,可以编写如下函数来创建SciChartSurface。
import {
SciChartSurface,
NumericAxis,
FastLineRenderableSeries,
XyDataSeries,
EllipsePointMarker,
SweepAnimation,
SciChartJsNavyTheme,
NumberRange
} from "scichart";
async function initSciChart() {
// 初始化 SciChartSurface。请不要忘记使用 await!
const { sciChartSurface, wasmContext } = await SciChartSurface.create("scichart-root", {
theme: new SciChartJsNavyTheme(),
title: "SciChart.js First Chart",
titleStyle: { fontSize: 22 }
});
// 使用 growBy 填充值创建 XAxis 和 YAxis
const growBy = new NumberRange(0.1, 0.1);
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "X 轴", growBy }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Y 轴", growBy }));
// 创建包含初始数据的折线图系列
sciChartSurface.renderableSeries.add(new FastLineRenderableSeries(wasmContext, {
stroke: "steelblue",
strokeThickness: 3,
dataSeries: new XyDataSeries(wasmContext, {
xValues: [0,1,2,3,4,5,6,7,8,9],
yValues: [0, 0.0998, 0.1986, 0.2955, 0.3894, 0.4794, 0.5646, 0.6442, 0.7173, 0.7833]
}),
pointMarker: new EllipsePointMarker(wasmContext, { width: 11, height: 11, fill: "#fff" }),
animation: new SweepAnimation({ duration: 300, fadeEffect: true })
}));
return { sciChartSurface };
}
步骤 4:创建 React 组件
可以使用 SciChartReact 组件来初始化图表。这将处理组件的整个生命周期,包括卸载时的删除操作。
function App() {
return (
<div className="App">
<SciChartReact initChart={initSciChart}
onInit={(initResult) => console.log(initResult.sciChartSurface.id + ` 已创建`);
onDelete={(initResult) => console.log(initResult.sciChartSurface.id + ` 已被删除`);
style={{ maxWidth: 900 }} />
</div>
);
}
查看示例运行效果
如需进一步了解,请在Github获取完整示例。
请参阅以下其他使用示例:
npm install
npm start
在 GitHub 上打开