首页 > 解决方案 > 轻量级图表不显示在 html 页面上

问题描述

我正在尝试使用 Lightweight-charts-library 在我的网页上使用图表,但图表不会显示。这是我的 HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type = "module" src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
    <title>Socket Streams</title>
</head>

<body>
    <h1>Trades</h1>

    <div id ="chart"></div>
    <div id ="trades"></div>



    <script>
        var binanceSockets = new WebSocket("wss://stream.binance.com:9443/ws/dogebtc@trade")
        var tradeDiv = document.getElementById('trades');

        binanceSockets.onmessage = function (event){
            console.log(event.data);
            var object = JSON.parse(event.data);
            tradeDiv.append(object.p);
        }   
         
    </script>


    <script src="chart.js" type="module"></script>
    
</body>
</html>

我的目标是在“图表”div 上显示一个图表,所以我基本上从 Lightweight-charts 库中复制粘贴了这段代码,使其指向图表。

import { createChart } from 'lightweight-charts';

const chart = createChart(document.getElementById("chart"), { width: 400, height: 300 });
const lineSeries = chart.addLineSeries();
lineSeries.setData([
    { time: '2019-04-11', value: 80.01 },
    { time: '2019-04-12', value: 96.63 },
    { time: '2019-04-13', value: 76.64 },
    { time: '2019-04-14', value: 81.89 },
    { time: '2019-04-15', value: 74.43 },
    { time: '2019-04-16', value: 80.01 },
    { time: '2019-04-17', value: 96.63 },
    { time: '2019-04-18', value: 76.64 },
    { time: '2019-04-19', value: 81.89 },
    { time: '2019-04-20', value: 74.43 },
]);

如果我type = module<script src="chart.js"></script>我得到Uncaught SyntaxError: Cannot use import statement outside a module。javascript的文件名是charts.js

标签: javascripthtmlchartslightweight-charts

解决方案


我假设您没有使用 webpack 或任何捆绑器。

module考虑,您需要以不同的方式导入库,并按照import 'https://unpkg.com/lightweight-charts@latest/dist/lightweight-charts.standalone.production.js';脚本中的chart.js说明进行操作,然后按照文档中的建议使用它。


推荐阅读