chart

김형우·2021년 12월 14일
0

Javascript

목록 보기
8/8
chart.html

차트 실습

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
            
    const ctx = document.getElementById("myChart")
                    .getContext("2d");
    
    // 표시할 chart의 데이터 및 색상 설정
    const config = {
        type : 'bar',
        data : {
            labels : ['A','B','C','D','E','F'],
            datasets : [{
                label : 'chart1',
                data:[23, 96, 76, 34, 35, 89],  // 여기 바꿀꺼다
                backgroundColor : [
                'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        }
    }

    // 실제로 chart가 생성되는 시점
    const myChart = new Chart(ctx, config);

    // 차트데이터변경
    const btn = document.querySelector('#btn');
    btn.addEventListener('click', () => {
        let data = config.data.datasets[0].data;

        // console.log(Math.random());  //0~1 사이의 숫자를 랜덤으로 발생
        // console.log(Math.random() * 100); //0 나올 수 있음
        // console.log(Math.random() * 100 + 1); //그래서 1을 더해줌
        // console.log(Math.floor(Math.random() * 100 + 1)); // Math.floor를 이용해 소숫점 이하 버림

        console.log(data);
        for(let i=0; i<6; i++){
            data[i] = Math.floor( Math.random() * 100 + 1);
        }

        // 변경된 데이터 적용해서 다시 그리기
        myChart.update();
    });
</script>    
profile
The best

0개의 댓글