实时通信 | pusher 案例:实时图表(七)

本文介绍了一种使用Google Charts和Pusher实现实时数据更新的方法。通过客户端JavaScript代码展示了一个基于面积图的比特币价格图表,并通过Pusher服务端定时推送随机价格数据实现动态更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建您的网页

<html>
<body>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://js.pusher.com/7.0.3/pusher.min.js"></script>
<script>
  google.charts.load("current", { packages: ["corechart"] });
  google.charts.setOnLoadCallback(() => {
    // Instead of hard-coding the initial table data,
    // you could fetch it from your server.
    const dataTable = google.visualization.arrayToDataTable([
      ["Year", "Price"],
      [2013, 400],
      [2014, 460],
    ]);
    const chart = new google.visualization.AreaChart(
        document.getElementById("chart_div")
    );
    const options = {
      title: "1 BTC in USD",
      hAxis: { title: "Year 2022 (Tinywan)", titleTextStyle: { color: "#333" } },
      vAxis: { minValue: 0 },
      animation: { duration: 100, easing: "out" },
    };
    chart.draw(dataTable, options);
    let year = 2015;
    Pusher.logToConsole = true;
    const pusher = new Pusher(
        "108365f54d1d934e7678", // Replace with 'key' from dashboard
        {
          cluster: "ap3", // Replace with 'cluster' from dashboard
          forceTLS: true,
        }
    );
    const channel = pusher.subscribe("price-btcusd");
    channel.bind("new-price", (data) => {
      const row = [year++, data.value];
      dataTable.addRow(row);
      chart.draw(dataTable, options);
    });
  });
</script>
</body>
</html>

服务端事件

<?php
/**
 * @desc pusher server
 * @author Tinywan(ShaoBo Wan)
 * @date 2022/01/29 23:02
 */
require_once '../../vendor/autoload.php';

$options = array(
    'cluster' => 'ap3',
    'useTLS' => true
);

$pusher = new Pusher\Pusher(
    '108365f54d1d934e7678',
    '9cfbfd3b06290c427de6',
    '1339434',
    $options
);

// Trigger a new random event every second. In your application,
// you should trigger the event based on real-world changes!
while (true) {
    $pusher->trigger('price-btcusd', 'new-price', array(
        'value' => rand(0, 5000)
    ));
    sleep(1);
}

效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tinywan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值