繁体   English   中英

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

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

现在,我所拥有的东西显示在这个小提琴中: 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
};

我的画布高度为400像素。 这就是我在这里用它作为参考的原因。 如果我需要添加更多详细信息,请与我们联系。

这是一个计划,有一个随机宽度的多边形,无限地向上滚动你的画布:

  • 保持形成多边形的随机X,增量-Y坐标数组。
  • 第一个元素array[0].y应该小于零。
  • 最后一个元素array[array.length-1].y应该大于画布高度。
  • 通过在每个动画循环期间将每个array.y减少1来进行动画处理。
  • 当array [1] .y减小到零以下时, shift数组[0]从数组的开头移开。
  • 当最后一个array.y被动画到可视画布上时,将一个新元素推入到array.y大于画布高度的数组中。

示例代码和演示:

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM