Animation 弹跳球动画:需要留下轨迹

Animation 弹跳球动画:需要留下轨迹,animation,canvas,simulation,game-physics,Animation,Canvas,Simulation,Game Physics,下面是一个反弹球的画布动画 我的问题是我想让球留下一条轨迹(一条标明球过去所在位置的线) 确定球位置的代码为: (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); //theta = Math.atan2(mouse.y-ball.y,mouse.x-ball.x);

下面是一个反弹球的画布动画

我的问题是我想让球留下一条轨迹(一条标明球过去所在位置的线)

确定球位置的代码为:

  (function drawFrame () {
    window.requestAnimationFrame(drawFrame, canvas);
    context.clearRect(0, 0, canvas.width, canvas.height);
    //theta = Math.atan2(mouse.y-ball.y,mouse.x-ball.x);

    ball.x += vx;
    ball.y += vy;
    if (ball.x > canvas.width - ball.radius) {
        ball.x = canvas.width - ball.radius;
        vx *= -1;
    } else if (ball.x < 0 + ball.radius){
        ball.x = 0 + ball.radius
        vx *= -1;
    }
    if (ball.y > canvas.height - ball.radius){
        ball.y = canvas.height - ball.radius
        vy *= -1;
    } else if (ball.y < 0 + ball.radius){
        ball.y = 0 + ball.radius;
        vy *= -1;
    }
    ball.draw(context);
  }());
(函数绘图框(){
window.requestAnimationFrame(绘图框、画布);
clearRect(0,0,canvas.width,canvas.height);
//θ=Math.atan2(mouse.y-ball.y,mouse.x-ball.x);
ball.x+=vx;
ball.y+=vy;
if(ball.x>canvas.width-ball.radius){
ball.x=canvas.width-ball.radius;
vx*=-1;
}否则如果(球x<0+球半径){
球体x=0+球体半径
vx*=-1;
}
if(ball.y>canvas.height-ball.radius){
ball.y=canvas.height-ball.radius
vy*=-1;
}否则如果(球y<0+球半径){
球体y=0+球体半径;
vy*=-1;
}
球。画(上下文);
}());
我的问题是,因为我使用的是clearRect(),所以我试图绘制的任何路径都会被删除。我所能做的就是不断地将ball.x和ball.y坐标添加到一个数组中,然后使用canvas lineTo()在每一帧中链接所有这些点,但这会很快到达大量点


有人能推荐一种方法吗?

现在看到,你想要一条线作为轨迹,而不仅仅是运动模糊中的轨迹

已为此更新小提琴:

在顶部添加一个新画布,您可以在其中绘制线条。这样你就避免了清理和保存所有东西

您可以简单地替换这一行:

context.clearRect(0, 0, canvas.width, canvas.height);
为此:

var tmp = context.fillStyle; //backup fillstyle

context.fillStyle = 'rgba(255,255,255,0.2)';
context.fillRect(0, 0, canvas.width, canvas.height);

context.fillStyle = tmp;
alpha通道值确定将获得多少轨迹(越少越好)

更新示例:

(注:我还修复了它,使其与Firefox配合使用-请参阅
requestAnimationFrame
polyfill-in-code)。

现在,您希望线作为轨迹,而不仅仅是运动模糊中的轨迹

已为此更新小提琴:

在顶部添加一个新画布,您可以在其中绘制线条。这样你就避免了清理和保存所有东西

您可以简单地替换这一行:

context.clearRect(0, 0, canvas.width, canvas.height);
为此:

var tmp = context.fillStyle; //backup fillstyle

context.fillStyle = 'rgba(255,255,255,0.2)';
context.fillRect(0, 0, canvas.width, canvas.height);

context.fillStyle = tmp;
alpha通道值确定将获得多少轨迹(越少越好)

更新示例:

(注:我还修复了它,使其与Firefox配合使用-请参阅
requestAnimationFrame
polyfill-in-code)。

以下是我将尝试的要点:在循环缓冲区中使用的x,y坐标集,每隔10集(或25集,或任何看起来不错的)保存最后一集。然后在绘制时,从最老的位置到最新的位置进行渲染,第一个位置的不透明度接近0,然后逐渐增加到当前位置的100。嗯,谢谢,但我真的很想要一个完整的历史。下面是我将尝试的一个概要:每10组(或25组,或任何看起来不错的)x保存最后一个位置,在循环缓冲区中使用的y坐标。然后当你画画时,从最老的位置到最新的位置渲染,第一个位置的不透明度接近0,然后逐渐增加到当前位置的100。嗯,谢谢,但我真的很想要一个完整的历史。