0

我的目标是指向屏幕内的不同位置,存储这些点 (x, y),并通过所有存储的 X 和 Y 值使我的图像具有动画效果。

我使用数组存储所有内容。以下是部分代码:

function storeCoordinates(e){
    pos.push({x:e.offsetX, y: e.offsetY });

    if(pos.length > 1){
        delta.push({
            dx: pos[pos.length - 1].x - pos[pos.length - 2].x,
            dy: pos[pos.length - 1].y - pos[pos.length - 2].y
        });
        //Distance between the two points
        distance[distance.length - 2] = Math.sqrt(delta[delta.length - 2].dx * delta[delta.length - 2].dx + delta[delta.length - 2].dy * delta[delta.length - 2].dy);

        moves[moves.length - 2] = distance[distance.length - 2] / speed;

        xunits[xunits.length - 2] =  (pos[pos.length - 1].x - pos[pos.length - 2].x) / moves[moves.length - 2];
        yunits[yunits.length - 2] = (pos[pos.length - 1].y - pos[pos.length - 2].y) / moves[moves.length - 2];
    }
}                                                      
c.addEventListener('click', function(e){storeCoordinates(e);}, false);

但是动画永远不会开始。任何帮助将非常感激!

完整的小提琴在这里

4

1 回答 1

1

您现有的代码存在多个问题。

这是您的代码的重构演示:http: //jsfiddle.net/m1erickson/9EZha/

关于对您的代码进行一些重构:

您可以像这样获得相对于画布的鼠标位置:

var mouseX=e.clientX-offsetX;
var mouseY=e.clientY-offsetY;

要沿多个点击点制作动画,您需要将每条线分解为沿线的点。

您可以从“pos”数组中创建一条多点线,如下所示:

function makePolyPoints(pathArray){

    var points=[];
    for(var i=1;i<pathArray.length;i++){
        var startPt=pathArray[i-1];
        var endPt=pathArray[i];
        var dx = endPt.x-startPt.x;
        var dy = endPt.y-startPt.y;
        for(var n=0;n<=100;n++){
            var x= startPt.x + dx * n/100;
            var y= startPt.y + dy * n/100;
            points.push({x:x,y:y});
        }
    }
    return(points);
}

您的动画功能应该:

  • 确定是否需要另一个循环(或者图像是否已完成动画)
  • 如果还有更多动画要做,请请求另一个动画帧。
  • 在折线上的当前位置绘制图像。
  • 沿着多段线递增到下一个位置。

以下是典型的动画循环可能的样子:

function animate(){

    // are we done animating?

    if(polyPos>polyline.length-1){return;}

    // request another animation frame

    requestAnimFrame(animate);

    // determine the current point on the polyline

    var pt=polyline[polyPos];

    // draw the image at the current point

    ctx.clearRect(0, 0, c.width, c.height);
    ctx.drawImage(car, pt.x, pt.y);

    // increment the next position on the polyline 
    // for the next animation frame

    polyPos++;
}
于 2013-11-05T23:59:57.177 回答