2016-11-14 77 views
2

我遇到了調整我的chart.js畫布大小的問題。 我已將畫布高度設置爲160,以便在更寬的屏幕上看起來不錯,但我需要將小高度更改爲300,以便在保持寬高比的同時不會看起來侷促。Chart.js更改窗口大小的高度,同時保持縱橫比

此外,我想添加一個onclick事件的酒吧,導致鏈接通過其各自的標籤的月份。

非常感謝這裏是我的代碼

<div> 
<canvas id="chart1" width="500" height="300"></canvas> 
</div> 

<script> 
var barLabel = <?php echo json_encode(array_reverse($ch1_arrDate)); ?>; 
var dataVal1 = <?php echo json_encode(array_reverse($ch1_arrRevenue_conf)); ?>; 
var barData = { 
    labels: barLabel, 
    datasets: [ 
     { 
      label: 'Confirmed Revenue', 
      backgroundColor: 'yellowgreen', 
      data: dataVal1, 

     }, 
    ] 
}; 

var barOptions = { 
    responsive: true, 
    maintainAspectRatio: true 
} 

var ctx = document.getElementById("chart1").getContext("2d"); 

if($(window).width()>748) 
    ctx.canvas.height = 160; 
else 
    ctx.canvas.height = 300; 

var chartDisplay = new Chart(ctx, { 
    type: 'bar', 
    data: barData, 
    options: barOptions 
}); 

$("#chart1").click( 
    function(evt){ 

    //supposed to when clicked goes to a linked href passing the month of the selected bar 
    // e.g dummy.php?month_year=vardate 
}); 

window.onresize = function() { 

//the window.onresize works but i dont know how to resize the canvas while maintaining the aspect ratio. 
if($(window).width()>748) 
    ctx.canvas.height = 160; 
else 
    ctx.canvas.height = 300; 

chartDisplay.resize(); 
} 
</script> 

bar graph

回答

0

我在這裏找到了一種通過重新裝入刷新新的高度,壽它可能不是最好的做法,以調整圖表。還發現了一種鏈接每個欄並將參數發送到另一頁的方法。看到下面的代碼。

<script> 
window.onresize=function(){ 
    $("#container").load("chart1.php"); 
} 

$("#container").load("chart1.php"); 
</script> 
在chart1.php

<?php 
//myqueries here for $ch1_arrDate,$ch1_arrRevenue_conf, and $ch1_arrDate2 
?> 
<div> 
    <canvas id="chart1" width="500" height="300"></canvas> 
</div> 


<script> 
$(document).ready(function(){ 
var barLabel = <?php echo json_encode(array_reverse($ch1_arrDate)); ?>; 
var dataVal1 = <?php echo json_encode(array_reverse($ch1_arrRevenue_conf)); ?>; 
var dateFilter = <?php echo json_encode(array_reverse($ch1_arrDate2)); ?>; 

var barData = { 
    labels: barLabel, 
    datasets: [ 
     { 
      label: 'Confirmed Revenue', 
      backgroundColor: 'yellowgreen', 
      data: dataVal1, 
     }, 
    ] 
}; 

var barOptions = { 
    responsive: true, 
    maintainAspectRatio: true 
} 


var ctx = document.getElementById("chart1").getContext("2d"); 

if($(window).width()>748) 
    ctx.canvas.height = 160; 
else 
    ctx.canvas.height = 300; 

var chartDisplay = new Chart(ctx, { 
    type: 'bar', 
    data: barData, 
    options: barOptions 
}); 

$("#chart1").click( 
    function(e){ 
     var activeBars = chartDisplay.getElementsAtEvent(e); 
     var index = activeBars[0]["_index"]; 
     location.href="dash_chartdeals.php?filter_date="+fixedEncodeURIComponent(dateFilter[index]); 
}); 
}); 
</script> 

在我dashboard.php

相關問題