2017-07-31 194 views
0

我使用Canvasjs創建燭臺圖表。這些值來自PHP,我使用JSON-encode將其轉換爲javascript數組。我用與例子相同的格式重新創建javascript數組,這是這樣的canvasjs顯示空白,數據未顯示

dataPoints=[{x: new Date(2012,01,01),y:[5198, 5629, 5159, 5385]}] 

但是畫布是空白的嗎?這裏是我的代碼:

<?php 


$chart_array[] = array("x"=>"2012-01-01","y"=>array("5198", "5629", "5159", "5385")); 
$chart_array[] = array("x"=>"2012-01-02","y"=>array("5366", "5499", "5135", "5295")); 

    $chart_array = json_encode($chart_array); 

?> 
    <script type="text/javascript"> 
     window.onload = function() { 


      var resultArray = <?php echo $chart_array; ?>; 

      var new_array = []; 
      jQuery.each(resultArray, function(index, item) { 

       new_array.push({ x: new Date(item.x), y: item.y }); 

      }); 

console.log(new_array); 
      var chart = new CanvasJS.Chart("chartContainer", { 
       title: { 
        text: "Basic Candle Stick Chart" 
       }, 
       zoomEnabled: true, 
       axisY: { 
        includeZero: false, 
        title: "Prices", 
        prefix: "$ " 
       }, 
       axisX: { 
        interval: 2, 
        intervalType: "month", 
        valueFormatString: "MMM-YY", 
       }, 
       data: [ 
       { 
        type: "candlestick", 
        dataPoints: new_array 
       } 
       ] 
      }); 
      chart.render(); 
     } 
    </script> 

console.log顯示數組存在。爲什麼顯示空白畫布?我如何解決?

+0

你有ID爲'chartContainer'一個div?例如'

' –

+0

你有jQuery和canvasjs鏈接?您將需要將數組值更改爲數字btw,例如'=>數組(5366,5499,5135,5295))' –

+0

我對數字使用了ParseInt,仍然是空白的? – mdnba50

回答

1

Y-value在您的代碼中似乎是字符串,應該是數字。即使將它存儲爲字符串,在將它傳遞給圖表選項之前將其解析爲數字也可以正常工作。

這裏是工作代碼:

<?php 

$chart_array[] = array("x"=>"2012-01-01","y"=>array(5198, 5629, 5159, 5385)); 
$chart_array[] = array("x"=>"2012-01-02","y"=>array(5366, 5499, 5135, 5295)); 

$chart_array = json_encode($chart_array); 
?> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> 

<script type="text/javascript"> 
    window.onload = function() { 
     var resultArray = <?php echo $chart_array; ?>; 

     var new_array = []; 
     jQuery.each(resultArray, function(index, item) { 
      new_array.push({ x: new Date(item.x), y: item.y }); 
     }); 

     var chart = new CanvasJS.Chart("chartContainer", { 
      title: { 
       text: "Basic Candle Stick Chart" 
      }, 
      zoomEnabled: true, 
      axisY: { 
       includeZero: false, 
       title: "Prices", 
       prefix: "$ " 
      }, 
      axisX: { 
       interval: 2, 
       intervalType: "month", 
       valueFormatString: "MMM-YY", 
      }, 
      data: [ 
      { 
       type: "candlestick", 
       dataPoints: new_array 
      } 
      ] 
     }); 
     chart.render(); 
    } 
</script> 

<div id="chartContainer" style="height: 300px; width: 100%;"></div>