+ 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