Why isn’t this variable working | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why isn’t this variable working

I’m trying to practice using the canvas since I’ve never used it before, so I tried just drawing a line. When I run it though, it says it can’t find a variable context in line 6. window.onload = function(){ var canvas= document.getElementById("canvas"); var context= canvas.getContext("2d") }; context.moveTo(10,10); context.lineTo(100,10); context.stroke();

2nd Jan 2022, 4:41 PM
ElizabethM
3 Answers
+ 5
Put everything inside the onload function
2nd Jan 2022, 4:45 PM
Lisa
Lisa - avatar
+ 4
ElizabethM Code outside the window.onload function is executing first. That's why.
2nd Jan 2022, 4:46 PM
A͢J
A͢J - avatar
0
// alert 2, alert 1 window.onload = function(){ alert(1); var canvas= document.getElementById("canvas"); var context= canvas.getContext("2d") }; alert(2); context.moveTo(10,10); context.lineTo(100,10); context.stroke();
2nd Jan 2022, 4:54 PM
FanYu
FanYu - avatar