티스토리 뷰

chart를 새로이 만들어 canvas 요소에 초기화하나 실제론 이전 chart가 지워지지 않고 그대로있는 문제.

hover 이벤트로 마우스를 chart위에서 움직일 시 이전 chart, 현재 chart가 빈번하게 바뀌며 화면에 나옵니다.

발생원인 : 검색 능력이 부족해 원인은 알 수 없었습니다.

new Chart(canvas, config);

짐작하기로는 new 연산자로 인한 새로운 메모리로 할당됨으로써 canvas를 초기화하는게 아닌 새로운 chart가 기존 chart위에 덧씌우듯 표시되는 문제라 사료됩니다.

해결방법 :

canvas 요소를 삭제하고 재생성하여 chart js를 초기화합니다.

var resetCanvas = function(){
  $('#results-graph').remove(); // this is my <canvas> element
  $('#graph-container').append('<canvas id="results-graph"><canvas>');
  canvas = document.querySelector('#results-graph');
  ctx = canvas.getContext('2d');
  ctx.canvas.width = $('#graph').width(); // resize to parent width
  ctx.canvas.height = $('#graph').height(); // resize to parent height
  var x = canvas.width/2;
  var y = canvas.height/2;
  ctx.font = '10pt Verdana';
  ctx.textAlign = 'center';
  ctx.fillText('This text is centered on the canvas', x, y);
};

 

canvas가 삭제되면서 기존 chart 또한 삭제되기에 이전과 같은 문제가 발생하지 않습니다.

출처 - https://stackoverflow.com/questions/24815851/how-to-clear-a-chart-from-a-canvas-so-that-hover-events-cannot-be-triggered

 

How to clear a chart from a canvas so that hover events cannot be triggered?

I'm using Chartjs to display a Line Chart and this works fine: // get line chart canvas var targetCanvas = document.getElementById('chartCanvas').getContext('2d'); // draw line chart var chart = ...

stackoverflow.com

 

ps. destory와 update를 활용하면 더욱 간단히 변경가능합니다.

destory는 말 그대로 기존 chart를 파괴하는 것이고

update는 기존 data만 변경하여 update하는 기능입니다.

https://www.chartjs.org/docs/3.5.0/developers/api.html

 

API | Chart.js

API For each chart, there are a set of global prototype methods on the shared chart type which you may find useful. These are available on all charts created with Chart.js, but for the examples, let's use a line chart we've made. .destroy() Use this to des

www.chartjs.org

 

댓글
공지사항