Javascript Canvas one item flickering -
i trying make objects move towards each other in canvas, when meet , overlap 1 should disappear , other should fall down. got animation that, 1 of items flickering.
<!doctype html> <html> <head> <style> canvas{border:#666 3px solid;} </style> </head> <body onload="draw(530,15); draw1(1,15);"> <canvas id="canvas" width="600" height="400"></canvas> <script> function draw(x,y){ var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.save(); ctx.clearrect(x, y, 600, 400); ctx.fillstyle = "rgba(0,200,0,1)"; ctx.fillrect (x, y, 70, 50); ctx.restore(); x -= 0.5; if(x==300) { return; }; var looptimer = settimeout('draw('+x+','+y+')',5); }; function draw1(w,e){ var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.save(); ctx.clearrect(w-1,e-2,600,400); ctx.fillstyle = "rgba(0,200,0,1)"; ctx.fillrect (w, e, 70, 50); ctx.restore(); w += 1; if(w==265) { w -= 1; e +=2; }; var looptimer = settimeout('draw1('+w+','+e+')',10); }; </script> </body> </html>
been trying 2 days, can't seem fix properly. in advance.
you rendering many frames per second forcing browser present frames. each time draw function returns browser presumes want present frame page.
animations need synced display refresh rate devices 60fps. have 1 render loop handles animation. call function via requestanimationframe
(raf) ensures animation stays in sync display hardware , browser rendering.
<!doctype html> <html> <head> <style> canvas{border:#666 3px solid;} </style> </head> <!-- dont need <body onload="draw(530,15); draw1(1,15);">--> <body> <canvas id="canvas" width="600" height="400"></canvas> <script> var canvas,ctx,x,y,w,e; var canvas,ctx,x,y,w,e; function draw() { ctx.fillstyle = "rgba(0,200,0,1)"; ctx.fillrect(x, y, 70, 50); }; function draw1(w, e) { ctx.fillstyle = "rgba(0,200,0,1)"; ctx.fillrect(w, e, 70, 50); }; function update(time){ // high precision time passed raf when calls function ctx.clearrect(0,0,canvas.width,canvas.height); // clear of canvas if(w + 70 >= x){ e += 2; }else{ x -= 0.75; w += 1; }; draw(x,y); draw1(w,e); requestanimationframe(update) // @ point function exits , browser presents // canvas bitmap display } function start(){ // set x = 530; y = 15; w = 1; e = 15; canvas = document.getelementbyid('canvas'); ctx = canvas.getcontext('2d'); requestanimationframe(update) } window.addeventlistener("load",start); </script> </body> </html>
Comments
Post a Comment