본문 바로가기
개발/Javascript

[Javascript] Chart.js radar chart 만들기

by devhooney 2022. 7. 27.
728x90

C#코드를 Java로 Converting 작업 중 차트가 있는데, radarChart.aspx로 만들어져 있었다.

나는 화면 쪽은 Javascript로 작업을 하고 있었기 때문에, 저 라이브러리를 사용할 수 없었다.

예전 회사에서 D3.js를 해봤지만, 복잡했던 기억이 있다.(공부를 제대로 안했다..)

그래서 간단하고 사용하기 편한 Chart.js를 사용했다.

 

일단 공홈에서 라이브러리를 다운받았다.

https://www.chartjs.org/docs/latest/

 

Chart.js | Chart.js

Chart.js (opens new window) Installation You can get the latest version of Chart.js from npm (opens new window), the GitHub releases (opens new window), or use a Chart.js CDN (opens new window). Detailed installation instructions can be found on the instal

www.chartjs.org

 

<th:block layout:fragment="script">
	<script type ="text/javascript" 
    th:src="@{https://cdn.jsdelivr.net/npm/chart.js@3.8.2/dist/chart.min.js}"></script>
</th:block>

<canvas id="radar-chart" width="400" height="400"></canvas>

화면에서 thymeleaf를 사용중이기 때문에 th:src~ 식으로 기입했다.

 

그리고 예시 코드를 넣었다.

const data = {
    labels: [
      'Eating',
      'Drinking',
      'Sleeping',
      'Designing',
      'Coding',
      'Cycling',
      'Running'
    ],
    datasets: [{
      label: 'My First Dataset',
      data: [65, 59, 90, 81, 56, 55, 40],
      fill: true,
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgb(255, 99, 132)',
      pointBackgroundColor: 'rgb(255, 99, 132)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgb(255, 99, 132)'
    }, {
      label: 'My Second Dataset',
      data: [28, 48, 40, 19, 96, 27, 100],
      fill: true,
      backgroundColor: 'rgba(54, 162, 235, 0.2)',
      borderColor: 'rgb(54, 162, 235)',
      pointBackgroundColor: 'rgb(54, 162, 235)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgb(54, 162, 235)'
    }]
  };

  const config = {
    type: 'radar',
    data: data,
    options: {
      elements: {
        line: {
          borderWidth: 3
        }
      }
    },
  };

  const ctx = document.getElementById('radar-chart');
  new Chart(ctx, config);

하지만 계속 빈 화면이 떴다..(에러와 함께)

왜이럴까..

구글링 결과

https://stackoverflow.com/questions/41280857/chart-js-failed-to-create-chart-cant-acquire-context-from-the-given-item

 

chart.js Failed to create chart: can't acquire context from the given item

I never got into node so I am pretty sure I am doing something massively wrong here since I cannot find any info at all by googling. I have a django site and I wanted a JS charting library, I chose

stackoverflow.com

 

위 코드를

document.addEventListener("DOMContentLoaded", function () {
	...(생략)...	
})

이렇게 해주면 됐다.

근데 사이즈가 너무크다.. 천천히 공홈에서 공부해보면서 적용해봐야겠다.

 

사이즈 수정은 options 안에 responsive: false를 해주면 된다.

이거 안해서 사이즈 안줄어서 답답했다.

 

기존 소스는 범위가 20씩이라 그런 옵션을 찾아서 넣어주었다.(scale~)

const config = {
    type: 'radar',
    data: data,
    options: {
      responsive: false,
      scale: {
        beginAtZero: true,
        max: 100,
        stepSize: 20,
      },
      elements: {
        line: {
          borderWidth: 3
        }
      }
    },
  };

 

위 스택오버플로우에서 찾은 내용에서 "DOMContentLoaded"가 나는 jQuery의 ready함수와 같다고 알고있었는데,

엄밀히 말하면 조금은 다르다.

https://jizard.tistory.com/307

 

DOMContentLoaded와 jQuery document.ready()의 중요한 차이점

포스팅을 보다보면 javascript의 DOMContentLoaded와 jQuery의 ready()가 동일하다고 설명되어있다. 결론부터 말하자면, 동일한 시점에 Trigger되는 것은 맞지만 이들의 작동방식에는 중요한 차이점이 있다. d

jizard.tistory.com

위 사이트에 잘 정리되어 있는데,

동일한 시점에 Trigger되는 것은 맞지만 이들의 작동방식에는 중요한 차이점이 있다.

 

DOMContentLoaded의 경우 addListener를 한 시점이 이미 이벤트가 일어난 시점(DOM이 준비되어버린)인 경우에는 호출되지 않는다.
반면에, ready()의 경우에는 이미 ready()를 호출하기 이전에 DOMContentLoaded 이벤트가 일어났더라도, ready안의 function이 호출된다.
API 통신을 통해 동적으로 집어넣은 Script에 DOMContentLoaded가 작동안되는 이유는 바로 이것이다!

 

라고 정리를 잘해주셨다.

아마 저렇게 동적으로 넣지 않는 이상 같다고 생각하고 사용해도 될것 같다.

 

예제 확인

https://codepen.io/gyeonghwanma/pen/YzObObR

 

YzObObR

...

codepen.io

 

728x90