С помощью диаграмм CanvasJS, как я могу иметь 2 диаграммы на одной странице при использовании функций диаграммы

#canvasjs

#canvasjs

Вопрос:

Вот мой код. Я исследовал онлайн, и я могу использовать только одно окно для загрузки, но у меня есть функции в моих диаграммах, которые я не могу удалить. Я пытался поместить коды диаграмм в функцию загрузки одного окна, но безрезультатно. Я также попытался поместить функции диаграммы с window.onload на две отдельные страницы и вызвать их на одной странице php, но это не работает (я предполагаю по тем же причинам). Спасибо 🙂

 <!DOCTYPE HTML>
<html>
<head>  

<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("bar", {
    animationEnabled: true,
    title:{
        text: "Maximum, Minimum and Average Temperatures for the Hot Cars"
    },
    axisY: {
        title: "Temperature (C)",
        includeZero: true
    },
    legend: {
        cursor:"pointer",
        itemclick : toggleDataSeries
    },
    toolTip: {
        shared: true,
        content: toolTipFormatter
    },
    data: [{
        type: "bar",
        showInLegend: true,
        name: "Maximum",
        color: "#fc0303",
        dataPoints: [
            <?php echo $black_max; ?>,
            <?php echo $white_max; ?>,
            <?php echo $red_max; ?>,
            <?php echo $clear_max; ?>,
            <?php echo $silver_max; ?>
        ]
    },
    {
        type: "bar",
        showInLegend: true,
        name: "Minimum",
        color: "#0314fc",
        dataPoints: [
            <?php echo $black_min; ?>,
            <?php echo $white_min; ?>,
            <?php echo $red_min; ?>,
            <?php echo $clear_min; ?>,
            <?php echo $silver_min; ?>
        ]
    },
    {
        type: "bar",
        showInLegend: true,
        name: "Average",
        color: "#b503fc",
        dataPoints: [
            <?php echo $black_avg; ?>,
            <?php echo $white_avg; ?>,
            <?php echo $red_avg; ?>,
            <?php echo $clear_avg; ?>,
            <?php echo $silver_avg; ?>
        ]
    }]
});
chart1.render();

function toolTipFormatter(e) {
    var str = "";
    var total = 0 ;
    var str3;
    var str2 ;
    for (var i = 0; i < e.entries.length; i  ){
        var str1 = "<span style= "color:" e.entries[i].dataSeries.color   "">"   e.entries[i].dataSeries.name   "</span>: <strong>"   e.entries[i].dataPoint.y   "</strong> <br/>" ;
        total = e.entries[i].dataPoint.y   total;
        str = str.concat(str1);
    }
    str2 = "<strong>"   e.entries[0].dataPoint.label   "</strong> <br/>";
    str3 = "<span style = "color:Tomato">Total: </span><strong>"   total   "</strong><br/>";
    return (str2.concat(str)).concat(str3);
}

function toggleDataSeries(e) {
    if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
        e.dataSeries.visible = false;
    }
    else {
        e.dataSeries.visible = true;
    }
    chart.render();
}}

window.onload = function () {
    var chart = new CanvasJS.Chart("line", {
    animationEnabled: true,
    zoomEnabled: true,
    title:{
        text: "Hot Cars Temperatures"
    },
    axisY:{
        title: "Temperature",
        lineColor: "#C24642",
        tickColor: "#C24642",
        labelFontColor: "#C24642",
        titleFontColor: "#C24642",
        includeZero: true,
        suffix: "C"
    },
    axisX: {
        title: "Time",
        titleFontColor:"#369EAD",
        lineColor:"#369EAD",
        tickColor:"#369EAD",
        labelFontColor:"#369EAD"  ,
        includeZero: true,
        suffix: " Mins"
      },
    toolTip: {
        shared: true
    },
    legend: {
        cursor: "pointer",
        itemclick: toggleDataSeries
    },
    data: [
        {
        type: "line",
        name: "White Temperatures",
        color: "#0d00ff",
        showInLegend: true,
        axisYIndex: 1,
        dataPoints: [<?php echo $white_data; ?>]
    },
    {
        type: "line",
        name: "Red Temperatures",
        color: "#ff1f1f",
        axisYIndex: 0,
        showInLegend: true,
        dataPoints: [<?php echo $red_data; ?>]
    },
    {
        type: "line",
        name: "Clear Temperatures",
        color: "#9d00ff",
        axisYIndex: 0,
        showInLegend: true,
        dataPoints: [<?php echo $clear_data; ?>]
    },
    {
        type: "line",
        name: "Silver Temperatures",
        color: "#bdbdbd",
        axisYIndex: 0,
        showInLegend: true,
        dataPoints: [<?php echo $silver_data; ?>]
    },
    {
        type: "line",
        name: "Black Temperatures",
        color: "#000000",
        axisYIndex: 0,
        showInLegend: true,
        dataPoints: [<?php echo $black_data; ?>]
    }]
});
chart.render();

function toggleDataSeries(e) {
    if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
        e.dataSeries.visible = false;
    } else {
        e.dataSeries.visible = true;
    }
    e.chart.render();
}}

</script>
</head>
<body>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>    
<div id="line" style="height: 370px; width: 75%;"></div>
<br>
<br>
<br>
<div id="bar" style="height: 370px; width: 75%;"></div>
</body>
</html>
  

Ответ №1:

window.onload запускается при загрузке всей страницы, включая ее содержимое (изображения, CSS, скрипты и т.д.). Вы можете создавать любое количество диаграмм в window.onload. Обратитесь к документации CanvasJS для получения руководства по рендерингу нескольких диаграмм на странице.

Ниже приведен рабочий код.

 <!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart1 = new CanvasJS.Chart("bar", {
  animationEnabled: true,
  title:{
      text: "Maximum, Minimum and Average Temperatures for the Hot Cars"
  },
  axisY: {
      title: "Temperature (C)",
      includeZero: true
  },
  legend: {
      cursor:"pointer",
      itemclick : toggleDataSeries
  },
  toolTip: {
      shared: true,
      content: toolTipFormatter
  },
  data: [{
      type: "bar",
      showInLegend: true,
      name: "Maximum",
      color: "#fc0303",
      dataPoints: [
          <?php echo $black_max; ?>,
          <?php echo $white_max; ?>,
          <?php echo $red_max; ?>,
          <?php echo $clear_max; ?>,
          <?php echo $silver_max; ?>
      ]
  },
  {
      type: "bar",
      showInLegend: true,
      name: "Minimum",
      color: "#0314fc",
      dataPoints: [
          <?php echo $black_min; ?>,
          <?php echo $white_min; ?>,
          <?php echo $red_min; ?>,
          <?php echo $clear_min; ?>,
          <?php echo $silver_min; ?>
      ]
  },
  {
      type: "bar",
      showInLegend: true,
      name: "Average",
      color: "#b503fc",
      dataPoints: [
          <?php echo $black_avg; ?>,
          <?php echo $white_avg; ?>,
          <?php echo $red_avg; ?>,
          <?php echo $clear_avg; ?>,
          <?php echo $silver_avg; ?>
      ]
  }]
});
chart1.render();

var chart2 = new CanvasJS.Chart("line", {
  animationEnabled: true,
  zoomEnabled: true,
  title:{
      text: "Hot Cars Temperatures"
  },
  axisY:{
      title: "Temperature",
      lineColor: "#C24642",
      tickColor: "#C24642",
      labelFontColor: "#C24642",
      titleFontColor: "#C24642",
      includeZero: true,
      suffix: "C"
  },
  axisX: {
      title: "Time",
      titleFontColor:"#369EAD",
      lineColor:"#369EAD",
      tickColor:"#369EAD",
      labelFontColor:"#369EAD"  ,
      includeZero: true,
      suffix: " Mins"
    },
  toolTip: {
      shared: true
  },
  legend: {
      cursor: "pointer",
      itemclick: toggleDataSeries
  },
  data: [
      {
      type: "line",
      name: "White Temperatures",
      color: "#0d00ff",
      showInLegend: true,
      axisYIndex: 1,
      dataPoints: [<?php echo $white_data; ?>]
  },
  {
      type: "line",
      name: "Red Temperatures",
      color: "#ff1f1f",
      axisYIndex: 0,
      showInLegend: true,
      dataPoints: [<?php echo $red_data; ?>]
  },
  {
      type: "line",
      name: "Clear Temperatures",
      color: "#9d00ff",
      axisYIndex: 0,
      showInLegend: true,
      dataPoints: [<?php echo $clear_data; ?>]
  },
  {
      type: "line",
      name: "Silver Temperatures",
      color: "#bdbdbd",
      axisYIndex: 0,
      showInLegend: true,
      dataPoints: [<?php echo $silver_data; ?>]
  },
  {
      type: "line",
      name: "Black Temperatures",
      color: "#000000",
      axisYIndex: 0,
      showInLegend: true,
      dataPoints: [<?php echo $black_data; ?>]
  }]
});
chart2.render();

function toolTipFormatter(e) {
  var str = "";
  var total = 0 ;
  var str3;
  var str2 ;
  for (var i = 0; i < e.entries.length; i  ){
      var str1 = "<span style= "color:" e.entries[i].dataSeries.color   "">"   e.entries[i].dataSeries.name   "</span>: <strong>"   e.entries[i].dataPoint.y   "</strong> <br/>" ;
      total = e.entries[i].dataPoint.y   total;
      str = str.concat(str1);
  }
  str2 = "<strong>"   e.entries[0].dataPoint.label   "</strong> <br/>";
  str3 = "<span style = "color:Tomato">Total: </span><strong>"   total   "</strong><br/>";
  return (str2.concat(str)).concat(str3);
}

function toggleDataSeries(e) {
  if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
      e.dataSeries.visible = false;
  } else {
      e.dataSeries.visible = true;
  }
  e.chart.render();
}
}

</script>
</head>
<body>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>    
<div id="line" style="height: 370px; width: 75%;"></div>
<br>
<br>
<br>
<div id="bar" style="height: 370px; width: 75%;"></div>
</body>
</html>