如何动态生成在 Canvas 中向上移动的多边形形状?

How can I dynamically generate a polygon shape that moves upward in Canvas?

现在,我所拥有的显示在这个 fiddle 中:https://jsfiddle.net/p0o5fvdm/

我想要的是多边形平滑地向上移动,并用更多的黑色填充它下面的部分,该颜色跨越随机宽度,与多边形对齐,并像顶部一样平滑地向上移动。我尝试使用以下代码,但它不保留原始多边形的形状,新多边形被绘制在旧多边形上,导致闪烁。

这是我的动画函数:

function animate(myShape, canvas, context, startTime) {

    var time = (new Date()).getTime() - startTime;

    myShape.y1 -= 1;
    myShape.y2 -= 1;
    myShape.y3 -= 1;


    context.clearRect(0, 0, canvas.width, canvas.height);

    drawShape(myShape, context);


    requestAnimFrame(function() {
      animate(myShape, canvas, context, startTime);
    });
}

我在 context.clearRect.

上方使用以下代码添加了以下代码以动态设置底边的宽度
if(myShape.y2 < 400) {
    myShape.y2 = 400;
    myShape.x2 = Math.random()*300;
    myShape.y3 = 400;
}

这是myShape的初始值:

var myShape = {
    x1: 200,
    y1: 0,
    x2: 120,
    y2: 400,
    x3: 0,
    y3: 400
};

我的 canvas 的高度为 400 像素。这就是为什么我在这里使用它作为参考。让我知道是否需要添加更多详细信息。

这是一个具有随机宽度的多边形的计划,可以无限向上滚动 canvas:

  • 保留构成多边形的随机 X、递增 Y 坐标数组。
  • 第一个元素 array[0].y 应小于零。
  • 最后一个元素 array[array.length-1].y 应该大于 canvas 高度。
  • 通过在每个动画循环期间将每个 array.y 减 1 来制作动画。
  • 当 array[1].y 减少到零以下时,shiftarray[0] 离开数组的开头。
  • 当最后一个 array.y 被动画化到视觉 canvas 上时,将一个新元素推入 array.y 大于 canvas 高度的数组。

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var a=[
    {x:rx(),y:-Math.random()*100},  // y above canvas
    {x:rx(),y:ry()}                 // y below canvas
];

// redraw
draw(a);

requestAnimationFrame(animate);

function animate(){
    // update - move all y's upward
    for(var i=0;i<a.length;i++){ a[i].y-=3; }
    // test if a[1] is off top of canvas
    if(a[1].y<0){a.shift();}
    // test if last a[] is on canvas
    if(a.length<2 || a[a.length-1].y<canvas.height){
        a.push({x:rx(),y:ry()});
    }
    // redraw
    draw(a);
    // request another animation loop
    requestAnimationFrame(animate);
}
//
function draw(a){
    ctx.clearRect(0,0,cw,ch);
    ctx.beginPath();
    ctx.moveTo(0,a[0].y);
    for(var i=0;i<a.length;i++){
        ctx.lineTo(a[i].x,a[i].y);
    }
    ctx.lineTo(0,a[a.length-1].y);
    ctx.fill();
}
//
function rx(){ return(canvas.width/2+Math.random()*200); }
function ry(){ return(canvas.height*1.25+Math.random()*canvas.height/2); }
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>