奇怪的动画行为

时间:2015-02-04 15:37:50

标签: javascript canvas

所以我想编码这个动画,它有一个等边三角形,有A,B和C点。目标是A朝B方向移动,B向C方向移动,C向A方向移动。它应该是有点螺旋向内,直到它关闭。我写了这个快速的画布程序来做到这一点,认为它只需要几分钟,但由于某种原因,它不会保持其形状为等边三角形。

jsfiddle here:http://jsfiddle.net/k3d8fbfg/

function Point(x, y) {
        this.ycoord=y;
        this.xcoord=x;
    }
    function init(){
      window.requestAnimationFrame(draw);
    }
    function getMagnitude(vx, vy) {
        return Math.sqrt(Math.pow(vx,2), Math.pow(vy,2));
    }
    var isPaused=false;
    function pause() {
        isPaused=(!isPaused);
    }
    var triangleSize=500;
    var point1=new Point(100, 100);
    var point2=new Point(point1.xcoord+triangleSize, point1.ycoord);
    var point3=new Point(point1.xcoord+(triangleSize/2), point1.ycoord+(triangleSize*.866025404));
    var count=0;
    function draw() {
        var canvas = document.getElementById("canvas");
        var ctx=canvas.getContext('2d');

        triangleSize-=1;

        count++;
        ctx.fillStyle="white";
        // if(count%3==0) 
            ctx.fillRect(0,0,canvas.width, canvas.height);

        ctx.beginPath();
        ctx.moveTo(point1.xcoord, point1.ycoord);
        ctx.lineTo(point2.xcoord, point2.ycoord);
        ctx.lineTo(point3.xcoord, point3.ycoord);
        ctx.closePath();
        ctx.stroke();
        ctx.fillStyle="black";
        ctx.fill();

        if(!isPaused) {
            var point1p=new Point(0,0),point2p=new Point(0,0),point3p=new Point(0,0);

            var diffVector1=new Point(point2.xcoord-point1.xcoord,point2.ycoord-point1.ycoord);
            var r=getMagnitude(diffVector1.xcoord, diffVector1.ycoord);
            diffVector1.xcoord/=r; diffVector1.ycoord/=r;
            console.log(getMagnitude(diffVector1.xcoord, diffVector1.ycoord)+" "+r);


            var diffVector2=new Point(point3.xcoord-point2.xcoord,point3.ycoord-point2.ycoord);
            r=getMagnitude(diffVector2.xcoord, diffVector2.ycoord);
            diffVector2.xcoord/=r; diffVector2.ycoord/=r;
            console.log(getMagnitude(diffVector2.xcoord, diffVector2.ycoord)+" "+r);


            var diffVector3=new Point(point1.xcoord-point3.xcoord,point1.ycoord-point3.ycoord);
            r=getMagnitude(diffVector3.xcoord, diffVector3.ycoord);
            diffVector3.xcoord/=r; diffVector3.ycoord/=r;
            console.log(getMagnitude(diffVector3.xcoord, diffVector3.ycoord)+" "+r);

            point1p.xcoord=point1.xcoord+diffVector1.xcoord; point1p.ycoord=point1.ycoord+diffVector1.ycoord;
            point2p.xcoord=point2.xcoord+diffVector2.xcoord; point2p.ycoord=point2.ycoord+diffVector2.ycoord;
            point3p.xcoord=point3.xcoord+diffVector3.xcoord; point3p.ycoord=point3.ycoord+diffVector3.ycoord;

            point1=point1p; point2=point2p; point3=point3p;
        }   


        window.requestAnimationFrame(draw);
    }
    init();

0 个答案:

没有答案