如何在HTML5画布上逐渐绘制线条动画 [英] How to progressively draw line animation in html5 canvas

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

问题描述

我正在使用画布。我画了一套线。这是我的示例代码

I am working with canvas. I have draw a set of lines. Here is my sample code

for(var i = 0 ; i< points.length; i++){
var point = points[i];

setInterval(function() {
  ctx.strokeStyle = "black";
  ctx.moveTo(point.startX, point.startY);
  ctx.lineTo(point.startX1, point.startY1); 
  ctx.stroke();
 }, 500);​
}

此代码每0.5秒绘制一条线。但我希望逐渐对其进行动画处理。
因此,请逐步帮助画线。

This code draws line after every 0.5 seconds. But I wish to animate it progressively. So kindly help to draw a line progressively.

此屏幕快照显示了输出。我在SVG中实现了这一点。但是我在画布上也需要相同的内容。

This screen shot show the output. I made this possible in SVG. But I need the same in canvas.

推荐答案

<!DOCTYPE html>
<html>
    <head>
        <title>Parent selector</title>
    </head>
<body>
<canvas height="300px" width="500px" id="canva"></canvas>
<script>
    var canva = document.getElementById('canva'),
        ctx = canva.getContext('2d');

    var Point = function (x, y) {
        this.startX = x;
        this.startY = y;
    };
    var points = [new Point(1, 2), 
                  new Point(10, 20), 
                  new Point(30, 30), 
                  new Point(40, 80), 
                  new Point(100, 100), 
                  new Point(120, 100)];

    //goto first point
    ctx.strokeStyle = "black";
    ctx.moveTo(points[0].startX, points[0].startY);

    var counter = 1,
    inter = setInterval(function() {
        //create interval, it will
        //iterate over pointes and when counter > length
        //will destroy itself
        var point = points[counter++];
        ctx.lineTo(point.startX, point.startY); 
        ctx.stroke();
        if (counter >= points.length) {
           clearInterval(inter);
        }
        console.log(counter);
    }, 500);
    ctx.stroke();
</script>
    </body>
</html>

这篇关于如何在HTML5画布上逐渐绘制线条动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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