Cannot read property 'getcontext' of null with Canvas

Hey folks,

I’ve been making a little HTML5 canvas tutorial, mostly for myself.

I’ve run into an issue where I get a TypeError: Cannot read property 'getContext' of null when the page first loads, but as soon as you run the code again it works fine.

Any ideas why this isn’t working first time?

Thanks!

Cells run asynchronously, and the grabExample does not know it has to wait for the example cell to yield.

You can fix your page by adding a name to the example cell, and make grabExample explicitely wait for it, like so:


(A more “observable” method might be to use the name example rather than the canvas id to grab the canvas.)

2 Likes

Perfect, thankyou! Yes - using the name would be more “Observable”, but I want to be able to replicate this stuff for myself in regular HTML/JS later :slight_smile:

If you want to take advantage of Observable’s reactive runtime and still run your code outside of Observable without modification you can download your notebook’s code.

1 Like

Yes! Which is awesome! Though I meant more that I need to learn how it works in regular HTML :slight_smile:

Sure, but you can use normal references in regular JavaScript, too, so there shouldn’t be a strong reason to prefer document.querySelector to grab a reference to the example canvas versus using a literal reference to example. And by using a reference rather than selecting through the DOM, Observable will track the references automatically.

1 Like

Interesting! I’ll look into that. Thankyou for the tip :slight_smile: