Files
vue-ts-example/src/components/iframe-page-comps/Iframe-PlotlyJs-Comp.vue
2025-04-18 12:05:53 +08:00

92 lines
2.7 KiB
Vue

<script setup lang="ts">
const src = computed(() => `${import.meta.env.BASE_URL}iframe/for-plotly.html`);
type I数据 = number[];
type WindowWithPlotly = Window & {
Plotly: typeof import('plotly.js-dist-min');
};
const iframeRef = useTemplateRef<HTMLIFrameElement>('iframeRef');
let contentWindow: null | WindowWithPlotly = null;
let 频谱图Element: import('plotly.js-dist-min').PlotlyHTMLElement | null = null;
// let 瀑布图Element: import('plotly.js-dist-min').PlotlyHTMLElement | null = null;
let _readyPromiseReslove = () => {};
const readyPromise = new Promise<void>((resolve) => {
_readyPromiseReslove = resolve;
});
const 频谱瀑布图Layout = {
title: '频谱瀑布图',
xaxis: {
title: '频率 (Hz)',
// range: [0, 22_050],
showgrid: false,
},
yaxis: {
title: '时间步',
showgrid: false,
},
margin: { l: 60, r: 40, b: 40, t: 60 },
};
const 频谱图Layout = {
title: '频谱图',
xaxis: {
title: '频率 (Hz)',
// range: [0, 22_050],
showgrid: true,
gridcolor: '#eee',
tickformat: ',d', // 设置为带逗号的整数格式 (推荐,更易读)
},
yaxis: {
title: '幅度 (dB)',
showgrid: true, // 显示网格线
gridcolor: '#eee',
tickformat: ',d', // 设置为带逗号的整数格式 (推荐,更易读)
},
margin: { l: 60, r: 40, b: 40, t: 60 },
} satisfies Partial<import('plotly.js-dist-min').Layout>;
defineExpose({
添加数据: async (DB数据: I数据, FFT大小: number /* 也叫快速傅里叶变换大小 */, 采样率: number) => {
const 频率分辨率 = 采样率 / FFT大小;
{
// 频谱图
console.debug('[添加数据被调用]', `数据.length :>> `, DB数据.length);
await readyPromise;
// 先清空之前的数据
await contentWindow!.Plotly.react(频谱图Element!, [], 频谱图Layout);
const x频率数据 = Array.from({ length: DB数据.length }, (_, i) => i * 频率分辨率);
await contentWindow!.Plotly.addTraces(频谱图Element!, {
x: x频率数据,
y: DB数据,
type: 'scatter',
line: { color: 'blue' },
});
}
{
// 瀑布图
}
},
});
async function onIframeLoad() {
console.debug('[onIframeLoad] iframe 加载完成');
contentWindow = iframeRef.value!.contentWindow as WindowWithPlotly;
频谱图Element = await contentWindow.Plotly.newPlot('PLOTLY_CHART_spectrogram', [], 频谱图Layout);
瀑布图Element = await contentWindow.Plotly.newPlot('PLOTLY_CHART_waterfall', [], 频谱瀑布图Layout);
_readyPromiseReslove();
}
onMounted(() => {
console.debug('[onMounted] comp 加载完成');
});
</script>
<template>
<iframe ref="iframeRef" @load="onIframeLoad" :src style="width: 100%; height: 100%; border: none" />
</template>