其他moveTo(x,y)canvas函数

时间:2013-10-11 20:18:12

标签: javascript html canvas

我正在寻找将我的形状设置为x,y位置的画布功能。 例如,我有一个数组,其中包含要绘制的所有形状,我只是“告诉”对象“动画到x,y坐标”,如下所示:

// Array that holds all the shapes to draw
var shapes = new Array();

// Setting up some shapes
for (var i = 0; i < 10; i++) {
    var x = Math.random()*250;
    var y = Math.random()*250;
    var width = height = Math.random()*30;
    shapes.push(new Shape(x, y, width, height));
};

function animate() {
    // Clear
    context.clearRect(0, 0, canvasWidth, canvasHeight);

    // Loop through every object
    var shapesLength = shapes.length;
    for (var i = 0; i < shapesLength; i++) {
        var tmpShape = shapes[i];

        //here should go function that would animate my shape to x,y postition
        var x = tmpShape.x????;
        var y = tmpShape.y????;

        // Draw
        context.fillRect(x, y, tmpShape.width, tmpShape.height);
    };

    setTimeout(animate, 33);
};

我没有尝试过任何事情,因为我根本不知道怎么做。

1 个答案:

答案 0 :(得分:1)

如果您沿着一条线从一个起点移动到终点,您可以像这样计算该行程的指定百分比的XY:

// pct goes from 0.00 to 1.00 as you go from the starting to ending points

var dx=endingX-startingX;
var dy=endingY-startingY;
var nextX=startingX+dx*pct;
var nextY=startingY+dy*pct;