+ 2

Undefined error - Passing to function (JavaScript)

Why do I get an undefined error when passing a canvasDrawing2dContext to my animate function? It works when I simply use my ctx variable globally, but I want to be able to pass it. The error is on line 59, could someone help me resolve this issue? I'm new to JS and I haven't come across this sort of issue in other languages. Thanks in advance! Here's my code: https://code.sololearn.com/WQoWCkgcp2Vf/?ref=app

3rd Aug 2018, 6:39 PM
bornToCode()
bornToCode() - avatar
4 Antworten
+ 3
1> you missuse requestAnimationFrame(): it take a function as argument wich could only get one parameter (a time stamp) https://developer.mozilla.org/fr/docs/Web/API/Window/requestAnimationFrame 2> you have an error in your circle objects initialization loop (missing parenthesis for the "y" call of Math.random(), wich result in a NaN value Corrected code (bad line commented, and added new ones below them): https://code.sololearn.com/WAECobc93n8c/?ref=app
3rd Aug 2018, 7:34 PM
visph
visph - avatar
+ 2
"globaly-like": your "ctx" context variable is defined in the scope of the anonymous function assigned to the onload event listener... as all of your code, so is available anywhere in your code ^^ You could also pass it to a specific function defined in another scope if needed, but in this case that's not necessary (and simplest to make readable/understandable correction) ;) Anyway, you could also use it "globaly-like" in your Circle() class...
3rd Aug 2018, 7:47 PM
visph
visph - avatar
0
Oh, I see, thank you so much! So I had to use ctx globally afterall, or at least in this case. I guess I need to study the API more. Thank you for the link too.
3rd Aug 2018, 7:39 PM
bornToCode()
bornToCode() - avatar
0
Wow, the scope can get complicated pretty quick here, lol. I was wanting to abstract the circle class into a shapes class and then pass a shapes object to the animate method that may actually be a circle, rectangle, or triangle etc. Thats why I was trying to make a more generalized animate function first; however, I can see that the requestAnimationFrame() method may keep me from doing that.
3rd Aug 2018, 7:58 PM
bornToCode()
bornToCode() - avatar