如何动画在画布上画线 [英] how to animate drawing lines on canvas
本文介绍了如何动画在画布上画线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经建立彼此在画布上连接一些行。现在,我想动画这些线路同时在画布上画画。
I have created some lines connecting with each other on canvas. Now I want to animate these lines while drawing on canvas.
任何人都可以请帮助?
这是我的code和提琴网址:
here is my code and 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();
推荐答案
我明白你的希望线逐步沿点在路径中使用动画扩展。
I understand that your want the lines to extend incrementally along the points in your path using animation.
一个演示: http://jsfiddle.net/m1erickson/7faRQ/
您可以使用此功能来计算沿路径航点:
// define the path to 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);
}
然后你可以使用requestAnimationFrame动画每个增量线段:
// calculate incremental points along the path
var points=calcWaypoints(vertices);
// variable to hold how many frames have elapsed in the animation
// t represents each waypoint along the path and is incremented in the animation loop
var t=1;
// start the animation
animate();
// incrementally draw additional line segments along the path
function animate(){
if(t<points.length-1){ requestAnimationFrame(animate); }
// draw a line segment from the last waypoint
// to the 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" to get the next waypoint
t++;
}
这篇关于如何动画在画布上画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文