LoginSignup
3
1

More than 3 years have passed since last update.

【chart.js】「Uncaught TypeError: Cannot read property 'getContext' of null」を解消する方法

Last updated at Posted at 2019-09-01

こんにちは!
ねこじょーかー(@nekojoker1234)と申します。

chart.js」を使用していると、デベロッパーツールのコンソール上で以下のようなエラーが出る場合があります。

スクリーンショット 2019-09-01 20.30.19.png

エラーメッセージを読み解くと、getContextnullになっていることがわかりますね。
getContextは、グラフ描画の最初で呼び出しています。

window.draw_graph = -> 
    ctx = document.getElementById("myChart").getContext('2d')

ここでエラーが出ているので、以下のようなチェック処理を入れてあげれば、エラーは出なくなります。

window.draw_graph = -> 
    if document.getElementById("myChart") == null
      return
    ctx = document.getElementById("myChart").getContext('2d')

アプリを使っている分には、画面上でエラーが出ることはないのですが、他のjavascriptが正常に動作しなかったりもしたので、この処理を入れておくことをおすすめします。

エラーメッセージを読むとturbolinksが影響していることがわかるので、公式ドキュメントには載っていないのでしょう。

Railsで開発している人は、要注意です。

あわせて読みたい

HTMLもわからない初心者が、独学で「投稿型SNSサービス」を作ったって本当?【193日間の死闘】

運営している PlayFab 専用ブログ
https://playfab-master.com

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1