如何在画布上动画绘制线条 [英] how to animate drawing lines on canvas

查看:56
本文介绍了如何在画布上动画绘制线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在画布上创建了一些相互连接的线条.现在我想在画布上绘制时为这些线条设置动画.

I have created some lines connecting with each other on canvas. Now I want to animate these lines while drawing on canvas.

有人可以帮忙吗?

这是我的代码和小提琴网址:

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();

http://jsfiddle.net/s4gWK/1/

推荐答案

我知道您希望线条使用动画沿着路径中的点逐渐延伸.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆