+ 3
const c=document.getElementById("cnvs"); var cnt; window.onload = function() { cnt = c.getContext("2d"); cnt.beginPath(); cnt.arc(150, 150, 150, 0, 2*Math.PI); cnt.stroke(); calc(); } function calc(){ //const dt = new Date(); cnt.beginPath(); cnt.moveTo(75,75); cnt.lineTo(150,150); }
25th Oct 2022, 7:26 PM
SoloProg
SoloProg - avatar
+ 2
Put all your variables and functions inside of onload. This ensures that the variables are defined, when the pages is loaded.
25th Oct 2022, 7:16 PM
Lisa
Lisa - avatar
+ 2
belal bayrakdar , I don't agree with Lisa's way "Put all your variables and functions inside of onload". You are going to know more about Windows onload when you get more expertise on this subject.
28th Oct 2022, 11:35 AM
SoloProg
SoloProg - avatar
+ 2
There are different ways to solve it. Pick the one you like best and suits whatever you try to do.
28th Oct 2022, 11:55 AM
Lisa
Lisa - avatar
+ 2
belal bayrakdar , I made it better there was just a tiny inaccuarcy. const c=document.getElementById("cn"); var cnt; window.onload = function() { cnt = c.getContext("2d"); cnt.beginPath(); cnt.arc(150, 150, 150, 0, 2*Math.PI); cnt.stroke(); draw(); // this calls the function } function draw() { let dt = new Date(); let mi = dt.getSeconds(); // dt.getMinutes(); let angle=(mi*6)*Math.PI/180; let xmi = 150*Math.sin(angle); let ymi = 150*Math.cos(angle); cnt.beginPath(); cnt.moveTo(150,150); cnt.lineTo(xmi+150,ymi+150); cnt.stroke(); setInterval(draw,1000); } https://www.sololearn.com/compiler-playground/WuNzKNwxFIW1
28th Oct 2022, 1:04 PM
SoloProg
SoloProg - avatar
+ 1
Yes. That is one of the easiest ways to make sure all variables and elements are defined when loading.
25th Oct 2022, 7:18 PM
Lisa
Lisa - avatar
+ 1
Great that you could fix it!
25th Oct 2022, 7:23 PM
Lisa
Lisa - avatar