Canvas' | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Canvas'

On my game I wanted to draw a circle in the centre. So I used the JS code but it didn't work. I had created a code which allows the canvas to fit the screen on different platforms, but i used the same variable but it didn't work and stated ctx is not defined. Can anyone help? The code: https://code.sololearn.com/WSLJ6Xc80J5K/#js

8th Jan 2018, 9:10 PM
Zakariya
Zakariya - avatar
7 Answers
+ 9
Hi Zak, The variable ctx was declared inside a function therefore its scope is localised to it. You are trying to use that variable again globally (outside its current scope) This article may help you https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/
8th Jan 2018, 10:04 PM
jay
jay - avatar
+ 8
Either make ctx global in scope or create a new variable ctx (which may be confusing for the reader, I would call it something else) If you want to make it global, at the top of the js put var ctx; that way there is little editing to do.
8th Jan 2018, 10:21 PM
jay
jay - avatar
+ 8
visph is correct.
8th Jan 2018, 10:28 PM
jay
jay - avatar
+ 3
Anyway, 'ctx' variable should be accessed only after init() was executed (in which 'ctx' is defined) ^^ I suggest to move the lines using 'ctx' to draw in canvas inside your init() function ;)
8th Jan 2018, 10:25 PM
visph
visph - avatar
+ 1
So I would have to create a separate variable defining ctx.
8th Jan 2018, 10:15 PM
Zakariya
Zakariya - avatar
0
I have attempted something, but it doesnt work. here it is: https://code.sololearn.com/WSLJ6Xc80J5K/?ref=app
8th Jan 2018, 10:25 PM
Zakariya
Zakariya - avatar
- 1
thanks.
8th Jan 2018, 10:28 PM
Zakariya
Zakariya - avatar