【问题标题】:Other moveTo(x,y) canvas function其他 moveTo(x,y) 画布函数
【发布时间】:2013-10-12 04:57:06
【问题描述】:

我正在寻找可以将我的形状动画到 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);
};

我什么都没试过,因为我根本不知道该怎么做。

【问题讨论】:

  • “要求代码的问题必须表明对正在解决的问题有最低限度的了解。包括尝试的解决方案、为什么它们不起作用以及预期的结果。”跨度>
  • 欢迎使用 Stackoverflow 并感谢您添加代码。我们通过在这里使用代码而茁壮成长!

标签: javascript html canvas


【解决方案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;

【讨论】:

  • 指定百分比是什么意思?
  • 所以如果 pct=0.00 那么你就在线段的起点。如果 pct=0.33 你从头到尾都是 1/3。如果 pct=1.00,则您处于线段的终点。
  • 知道了。顺便说一句,我正在搜索 thisthis 之类的东西,但是是直线
  • 是的,这个公式将在任何起点 [startingX,startingY] 和任何终点 [endingX,endingY] 之间导航一条直线,您可以通过清除画布和上下文来“移动”形状.fillRect(newX,newY,shape.width,shape.height)
  • 最后一个问题:NO。您想在动画循环中将 pct 从 0.00 增加到 1.00 以计算从开始到结束的线的 XY。
猜你喜欢
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 2022-06-19
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多