javascript - slowly animate a simple line -


my problem line draw instantaneous.

what want draw line slowly, 3-5 seconds before finishes @ dy. reason cannot settimeout() work. have tried large , small values.

i have basic line example expand on concept include x , bezier lines once can figure how timeout works.

var canvas = document.getelementbyid('mycanvas'); var context = canvas.getcontext('2d');  function myline(x, y, dx, dy) { //line constructor   this.x = x; //start x   this.y = y; //start y   this.dx = dx; //end x   this.dy = dy; //end y } var line = new myline(100, 5, 100, 100); //line object  function drawline(myline, context) { //draw function     context.moveto(myline.x, myline.y);        animate(line, context);   } function animate(myline, context) { //animation function     if (myline.y < myline.dy) {       myline.y = myline.y + 1;       context.lineto(myline.dx, myline.y);       context.stroke();       window.settimeout(animate(line, context), 1000/60);     } } drawline(line, context); 

that's not want do: computers don't things "slowly", not in context single-threaded. want instead draw lots of lines, on , over, each next line little longer previous one. way, looks line growing, , want:

function drawline(x1,y1,x2,y2,ratio) {   ctx.fillrect(0,0,300,300);   ctx.beginpath();   ctx.moveto(x1,y1);   x2 = x1 + ratio * (x2-x1);   y2 = y1 + ratio * (y2-y1);   ctx.lineto(x2,y2);   ctx.stroke();   // , if intend start new things after   // this, , part of outline,    // want ctx.closepath() }  function animate(ratio) {   ratio = ratio || 0;   drawline(0,0,300,300,ratio);   if(ratio<1) {     requestanimationframe(function() {       animate(ratio + 0.01);     });   } }  animate(); 

running code: http://jsbin.com/hanaqahoyu/edit?html,js,output

also note do not want use settimeout: in order ensure smooth animation, modern browsers have requestanimationframe, going trigger when makes sense frame of animation, super handy: we'll use that.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -