CanvasJS HTML5 JavaScript Charts

CanvasJS helps you create chart in the most simple and efficient way possible

by ttquang1063750

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<button onclick="toggle()">
  Stacked Column / Area
</button>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

CSS

button{
    display: block;
    padding: 10px;
    margin: 10px auto;
    border: none;
    background: green;
    color: white;
    font-size: 16px;
}

JavaScript

let type = 'stackedColumn';
let chart = new CanvasJS.Chart("chartContainer",
{
    title:{
        text: "A Stacked Area Chart"
        
    },   
    legend: {
        verticalAlign: "bottom",
        horizontalAlign: "center",
        cursor:"pointer",
        maxWidth: 460,
        itemclick: (e) => {
            if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
                e.dataSeries.visible = false;
            } else {
                e.dataSeries.visible = true;
            }
            
            e.chart.render();
        }
    },
    data: [
        {        
            type: "stackedColumn",
            name:"In 1",
            showInLegend: true,
            dataPoints: [
                { x: 10, y: 5 },
                { x: 10, y: -5 },
                { x: 20, y: 15},
                { x: 30, y: 20 }
            ]
        },
        {        
            type: "stackedColumn",
            showInLegend: true,
            name:"Out 1",
            dataPoints: [
                { x: 10, y: -5 },
                { x: 20, y: -7},
                { x: 30, y: -8 },
                { x: 30, y: 5 }
            ]
        }
    ]
});




function toggle() {
    if(type === 'stackedColumn'){
        type = 'stackedArea';
    }else{
        type = 'stackedColumn'
    }
    chart.options.data.forEach(d => {
        d.type = type;
    });
    chart.render();
}

chart.render();