what's wrong? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

what's wrong?

14th Feb 2017, 8:01 AM
Prabhakar Dev
Prabhakar Dev - avatar
2 Answers
+ 6
var canvas = document.getElementById("canvas"); canvas.width = 400; canvas.height = 200; ctx = canvas.getContext("2d"); var points = [], currentPoint = 1, nextTime = new Date().getTime()+500, pace = 200; // make some points for (var i = 0; i < 50; i++) { points.push({ x: i * (canvas.width/50), y: 100+Math.sin(i) * 10 }); } function draw() { if(new Date().getTime() > nextTime){ nextTime = new Date().getTime() + pace; currentPoint++; if(currentPoint > points.length){ currentPoint = 0; } } ctx.clearRect(0,0,canvas.width, canvas.height); ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); ctx.lineWidth = 2; ctx.strokeStyle = '#2068A8'; ctx.fillStyle = '#2068A8'; for (var p = 1, plen = currentPoint; p < plen; p++) { ctx.lineTo(points[p].x, points[p].y); } ctx.stroke(); requestAnimFrame(draw); } setInterval(draw,1000)
14th Feb 2017, 8:02 AM
Prabhakar Dev
Prabhakar Dev - avatar
+ 2
Few points... but works as is, if correctly linked to correct html, even with an JS error :P The non-blocking error is about the use of 'requestAnimFrame' identifier, which is not declared, and have not syntax corresponding to the built-in method of the 'window' object ( 'window.requestAnimationFrame()' )... For use it, you need a few more adaptation, that I detail in comment on the code below ;) The other non-troublesome mistake, as is, is the doucle use of setInterval() and requestAnimationFrame() methods, who have almost the same behaviour, so if there wasn't the first error, you will have two instances of refresh running, accelerating the animation... Finally, and before the corrected/commented code, let say that to study yours, I reformat a minimum it, by proper indent, line breaks add: try to present more readable code, and better context if you guess help ( the html context wasn't provided, so I have imagine a simple <div id="canvas"></div> to tes/debug it... if you don't have this kind, you still have also troublesome with the getElementById() method ^^ ) ... the code: https://code.sololearn.com/WoC1dSv8M4KS/#js
14th Feb 2017, 12:11 PM
visph
visph - avatar