Chart.js如何在窗口调整大小时保持宽高比例并改变高度

3
我遇到了调整chart.js画布大小的问题。我将画布高度设置为160,以便在更宽的屏幕上看起来好看,但是在小屏幕上我需要将高度更改为300,以保持其纵横比并且不会显得拥挤。
此外,我想在条形图上添加一个单击事件,该事件可以将其相应标签的月份传递给链接。
谢谢。以下是我的代码:
<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>

柱状图

(涉及IT技术)
1个回答

0

我找到了一种方法来重新加载图表以刷新新的高度来调整其大小,尽管这可能不是最佳实践。还发现了一种方法来链接每个条形并向另一个页面发送参数。请参见以下代码。

在我的dashboard.php文件中:

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

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

in 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接