在Chart.js中实现范围滑块

blmhpbnm  于 2023-05-06  发布在  Chart.js
关注(0)|答案(1)|浏览(203)

我目前正在尝试使用范围滑块来操纵Chart.js图表上的条形图。然而,即使我写了代码,我从以前的项目中使用,它仍然无法工作。我附上了下面的代码,如果有人能告诉我为什么点击滑动范围滑块不会改变条形图。
我有两段主要的代码:

<input type="range" class="slider" value="5" min="30" max="50" id="points" onchange="function()">

var heating [] =  parseInt(document.querySelector('#points').value);

本质上,加热变量被分配给它,然后通过onchange运行函数。我不知道为什么现在还没有。如果有人能检查一下,那就太好了。我附上下面的所有代码。

索引.HTML文件

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lobster|Montserrat|Tangerine">
</head>
<body>
  <div id="chart-container">
    <canvas id="chart" style="font-family: 'Tangerine', serif; font-size: 1.9em;"></canvas>
    <form action="test.php" method="get">
      <label>BlockGroup<input  class="flex-wrapper"  type="text" name="BlockGroup"  placeholder="60014431031" ><br><br>    
        <label>Zip Code: <input style=" display:inline;" class="flex-wrapper"   type="text" name="ZipCode"  placeholder="94538"><br><br>    
        <label>City: <input style=" display:inline;" class="flex-wrapper"   type="text" name="City"  placeholder="Fremont"><br><br>    
        <label>State: <input style=" display:inline;" class="flex-wrapper" type="text" name="State"  placeholder="California"><br><br>    
        <!-- <label>County: <input style=" display:inline;" class="flex-wrapper"  id="myInput" type="text" name="County"  placeholder="Alameda" value='<?php echo $firstname; ?>' ><br><br> -->    
        <input type="submit" value="Submit">    
    </form>    
  </div>    
  <button id="shuffle">Sort Data</button>    
  <br>
  <p> <b> Heating Electrification <b> <p>
    <input type="range" class="slider" value="5" min="30" max="50"  id="points" onchange="function()">    
  <!-- javascript -->
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
  <script type="text/javascript" src="app.js"></script>    
</body>
</html>

APP.JS

const CHART = document.getElementById("chart");
var barChart = [];

Chart.defaults.global.animation.duration = 3000;
Chart.plugins.register({
  beforeUpdate: function(chart) {
    if (chart.options.sort) {
      // Get the data from each datasets.
      var dataArray = [];
      $.each(chart.data.datasets, function() {
        dataArray.push(this.data);
      });
      // Get the index after sorted.
      let dataIndexes = dataArray.map((d, i) => i);
      dataIndexes.sort((a, b) => {
        return dataArray[a] - dataArray[b];
      });
      // create after sorted datasets.
      var tempDatasets = [];
      $.each(dataIndexes, function() {
        tempDatasets.push(chart.data.datasets[this]);
      });
      // apply it
      chart.data.datasets = tempDatasets;
      return tempDatasets;
    }
  }
});

$(document).ready(function() {
  $.ajax({
    url: "http://localhost:8888/test.php",
    method: "GET",
    success: function(data) {
      console.log(data);
      var sample = [];
      var electric = [];
      var mpg = [];
      var urban = [];
      var vmt = [];
      var airtravel = [];
      var renewable = [];
      var conservation = [];
      var heating = [];
      var water = [];
      var cefficiency = [];
      var shiftc = [];
      var healthyd = [];
      var heating[] = parseInt(document.querySelector('#points').value);

      for (var i in data) {
        sample.push(data[i].sample);
        electric.push(parseInt(data[i].electric));
        mpg.push(parseInt(data[i].mpg));
        urban.push(parseInt(data[i].urban));
        vmt.push(parseInt(data[i].vmt));
        airtravel.push(parseInt(data[i].airtravel));
        renewable.push(parseInt(data[i].renewable));
        conservation.push(parseInt(data[i].conservation));
        heating.push(parseInt(data[i].heating));
        water.push(parseInt(data[i].water));
        cefficiency.push(parseInt(data[i].cefficiency));
        shiftc.push(parseInt(data[i].shiftc));
        healthyd.push(parseInt(data[i].healthyd));
      }

      var chartdata = {
        labels: sample,
        datasets: [{
            label: "Electric Vehicles",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: electric,
            stack: 1
          },
          {
            label: "50+ MPG Vehicles",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: mpg,
            stack: 2
          },
          {
            label: "Urban Infill",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: urban,
            stack: 3
          },
          {
            label: "VMT Reduction",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: vmt,
            stack: 4
          },
          {
            label: "Air Travel Reduction",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: airtravel,
            stack: 5
          },
          {
            label: "Renewable Electricity",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: renewable,
            stack: 6
          },
          {
            label: "Energy Eficiency and Conservation",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: conservation,
            stack: 7
          },
          {
            label: "Heating Electrification",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: heating,
            stack: 8
          },
          {
            label: "Water & Waste",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: water,
            stack: 9
          },
          {
            label: "Commercial Efficiency",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: cefficiency,
            stack: 10
          },

          {
            label: "Shift Consumption",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: shiftc,
            stack: 11
          },
          {
            label: "Healthy Diets",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: healthyd,
            stack: 12
          },
        ]
      };

      barChart = new Chart(CHART, {
        type: 'horizontalBar',
        data: chartdata,
      });

    },
    error: function(data) {
      console.log(data);
    }
  });
});

document.getElementById('shuffle').addEventListener('click', function() {
  barChart.options.sort = true;
  barChart.update();
  barChart.options.sort = true;
});

另外,这里是上述情况的图片。当滑动我的范围滑块时,什么也没有发生,所以我有点担心:

rbpvctlc

rbpvctlc1#

你还能有动力去解决这个问题吗?
这是一件很容易的事情,真的。但是,您需要了解更多一点它是如何工作的。
首先,您在$(document).ready上编写了此代码,这意味着此代码仅在页面就绪后运行。(一次)图表无法更新。

var heating[] = parseInt(document.querySelector('#points').value);

您还添加了事件。

<input type="range" class="slider" value="5" min="30" max="50" id="points" onchange="function()">

这个事实告诉我你真的不明白事情。通常,你需要调用一个函数,像这样。

<input type="range" class="slider" value="5" min="30" max="50" id="points" onchange="testFunction()">

function testFunction() {
    // update chart...
}

或者添加事件(这次我使用jQuery)

<input type="range" class="slider" value="5" min="30" max="50" id="points">

$("#points").on("change", function() {
    // update chart...
});

最后,要更新Chart.js,您需要更新数据集中的值,并调用其update方法。您可以只更新一个数据集。

// Get heating datasets. (Yes, you can write 'barGraph.data.datasets[7].data = xxx')
var heatDatasts = barGraph.data.datasets[7];
// Update value
heatDatasts.data = [$(this).val()];
// Apply it to the view.
barGraph.update();

如果你不能使用调试工具,我建议至少使用一个警告。(我在jsfiddle中使用)
这样你就可以知道代码是否运行了。
Example

已更新1

第一个问题。
我更新了图像,希望你能理解。
有各种各样的方法,但我选择了两种。

/*************** Pattern1 (Simply, using jQuery each) ***************/
// Loop
$.each(barGraph.data.datasets, function() {
    // Check the label or stack, in this case.
    if (this.label === "Heating Electrification") {
        // It's okay
        // heatDatasets = this;
        // Set value is also okay.
        this.data = [sliderValue];
        return false;
    }
});
 /*************** Pattern2 (using jQuery grep or filter)***************/
 var heatDatasets = $.grep(barGraph.data.datasets, function(datasets) {
     return (datasets.label === "Heating Electrification");
 })[0];
 heatDatasets.data = [sliderValue];

第二项质询。
基本上,我们不会在HTML上使用JavaScript变量。不过,一些框架或库看起来是可能的。

// Set value, min and max.
// We can't use JavaScript variable on HTML, usually.
var slider = $("#points");
slider.prop("min", 0);
slider.prop("max", 1000);
slider.val(1000);

For example

已更新2

我发现数据集可以有任何参数,所以你可以添加任何参数。
例如,我添加了'barId'并修改了滑块(添加id,与'barId'相同)。
For example

相关问题