javascript - how to animate drawing lines on canvas -


i have created lines connecting each other on canvas. want animate these lines while drawing on canvas.

can please help?

here code , fiddle url:

var c=document.getelementbyid("mycanvas"); var ctx=c.getcontext("2d"); ctx.moveto(0,0,0,0); ctx.lineto(300,100); ctx.stroke();  ctx.moveto(0,0,0,0); ctx.lineto(10,100); ctx.stroke();  ctx.moveto(10,100,0,0); ctx.lineto(80,200); ctx.stroke();  ctx.moveto(80,200,0,0); ctx.lineto(300,100); ctx.stroke(); 

http://jsfiddle.net/s4gwk/1/

i understand want lines extend incrementally along points in path using animation.

a demo: http://jsfiddle.net/m1erickson/7farq/

you can use function calculate waypoints along path:

// define path plot var vertices=[]; vertices.push({x:0,y:0}); vertices.push({x:300,y:100}); vertices.push({x:80,y:200}); vertices.push({x:10,y:100}); vertices.push({x:0,y:0});  // calc waypoints traveling along vertices function calcwaypoints(vertices){     var waypoints=[];     for(var i=1;i<vertices.length;i++){         var pt0=vertices[i-1];         var pt1=vertices[i];         var dx=pt1.x-pt0.x;         var dy=pt1.y-pt0.y;         for(var j=0;j<100;j++){             var x=pt0.x+dx*j/100;             var y=pt0.y+dy*j/100;             waypoints.push({x:x,y:y});         }     }     return(waypoints); } 

then can use requestanimationframe animate each incremental line segment:

// calculate incremental points along path var points=calcwaypoints(vertices);   // variable hold how many frames have elapsed in animation // t represents each waypoint along path , incremented in animation loop var t=1;   // start animation animate();  // incrementally draw additional line segments along path function animate(){     if(t<points.length-1){ requestanimationframe(animate); }     // draw line segment last waypoint     // current waypoint     ctx.beginpath();     ctx.moveto(points[t-1].x,points[t-1].y);     ctx.lineto(points[t].x,points[t].y);     ctx.stroke();     // increment "t" next waypoint     t++; } 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -