Why my context is not defined shown in here? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why my context is not defined shown in here?

https://code.sololearn.com/WT8WwZKjZiL4/?ref=app

9th Aug 2022, 5:12 AM
Samit Shrestha
Samit Shrestha - avatar
1 Answer
+ 4
The javascript is loaded before HTML body, so "body" doesn't exist right when you search it in javascript. The easy way is to wrap alll the code in a window.onload = function(){ //your code } //I suggest you search some more info about window.onload window.onload = function(){ var canvas = document.createElement("canvas") document.body.appendChild(canvas) /*canvas.width = 300px canvas.height = 300px*/ var context = canvas.getContext('2d') context.fillStyle = 'green' context.fillRect(0, 0, 10, 10) var x = 0 window.requestAnimationFrame(function loop() { x += 1 context.fillStyle = 'red' context.fillRect(0, 0, 100, 100) }) }
9th Aug 2022, 5:21 AM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar