javascript - Html5 canvas animation. How to reset rectangle when it hits the end -


hey im experimenting html5 animation , far have square "falls" whenever press button. wondering how have go top when hits bottom , fall again. current code is:

<html> <head> </head> <body>  <canvas id="mycanvas" width="200" height="400" style="border:1px solid black;"> browser not support html5 canvas tag. </canvas>  <script> function draw (x,y){ var c = document.getelementbyid("mycanvas"); var ctx = c.getcontext("2d"); ctx.save(); var side = 10 var = 10 ctx.clearrect(0,0,200,400); ctx.fillstyle = "#ff0000"; ctx.fillrect(x,y,up,side); ctx.restore(); y += 5; var looptimer = settimeout('draw('+x+','+y+')',30); }   </script>  <button onclick="draw(0,0)">draw</button> </body> </html> 

using variables y, can check if below height of canvas height.

if( y > c.height ){ // use canvas height, not context height    y = 0; } 

also, way you're calling timer bit inefficient. instead of :

var looptimer = settimeout('draw('+x+','+y+')',30); 

i recommend

var looptimer = settimeout(function(){ draw(x,y); },30); 

here's working example: http://jsfiddle.net/vwcdplvv/


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -