When updating Chart.js chart the data is updated but canvas is emptied

时间:2018-07-24 10:09:59

标签: javascript canvas chart.js

I'm creating multiple charts in my html page with Chart.js and after window has loaded charts are updated dynamically in every second with new data values. I'm handling the updating with Chart.js update() function. All created charts are stored in global array where those are then fetched to be updated.

Updating works as it should when I first time open my html page and graphs are updated every second(showing live measured data), but when I move to another subpage in my webapp and then return back to the page where graphs should be, all canvases are empty(data in charts is updating as it should but canvases stays blank).

When I'm moving to subpage I'm only updating part of the html content including area where those canvases are and when I'm returning to frontpage I load that same area with same html content than first time when I open my webpage.

So currently what I'm doing is that when I return to page where charts should be rendered I fetch old charts from global chart-array(created when webpage is first time opened), replacing old datasets with new ones and then calling the Chart.js update() function. I know that the datasets are updated every second like they did when I open webpage first time as I wanted(I check this with console) but canvases are emptied so those updated charts are not shown anywhere anymore.

This is my canvas when updating works properly:

<canvas id="etaisyyskuvaaja" height="200" width="350" class="chartjs-render-monitor" style="display: block; touch-action: none; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></canvas>

And this is how it looks like when trying to update after returning from subpage:

<canvas id="etaisyyskuvaaja"></canvas>

So that's what I mean with "emptied".

I thought that when I'm updating old chart that has once been created in specific canvas it should be automatically rendered to that same canvas when data is updated (actually this does work this way when html content stays the same when I first time open webpage). However now it seems that re-rendering doesn't work anymore when I have changed html content (moved to subpage) and then loaded those canvases again (returning to frontpage and start cyclic updating again).

Can someone tell why my charts are updated with new data as they should but canvases are emptied?

1 个答案:

答案 0 :(得分:0)

首先,我认为如果图表实例在删除html内容后确实错过了原始画布,然后又将其重新加载,则可能需要再次获取canvas元素并将其以某种方式传递给update-function。

但是我无法找到更新画布的解决方案,因此我设法解决了以下问题:

返回首页时,我首先遍历图表数组并删除所有应该位于首页中的图表(上次加载首页时创建)。然后,在加载html内容之后,我再次创建那些图表,并将它们保存在我的图表数组中。现在,当我开始对这些新创建的图表进行周期性更新时,更新再次像超级按钮一样起作用!