试图在有丝分裂模拟中激活细胞分裂

Trying to animate division of cell in mitosis sim

我正在制作一个有丝分裂模拟器,我希望它在细胞足够大并分裂时 运行 有丝分裂功能。当它拆分时,我希望它能够将初始 x 值(前一个单元格的 x)拆分为新的 x 值(右侧的 x+10)。我已经尝试使用循环和 setTimeout() 来查看是否可以延迟添加 x 以尝试为其设置动画,但我似乎无法让它工作。我以前从未在 JS 中使用过动画,因此非常感谢任何建议。

    <html>
    <head>
    <title>Mitosis</title>
    </head>
    <body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script>
        let c = document.getElementById("canvas");
        let ctx = c.getContext("2d");
        let cells = [];
        cells.push(new Cell(100,100,5));
        function Cell(x,y,r) {
            this.x = x;
            this.y = y;
            this.r = r;
        }
        function update() {

            move();

            draw();
            if(cells.length < 50) {
                grow();
            }
        }
        setInterval(update,100);
        function draw() {
            ctx.clearRect(0,0,500,500)
            for(let i = 0, len = cells.length; i < len; i++) {
                ctx.beginPath();
                ctx.arc(cells[i].x,cells[i].y,cells[i].r,0,2*Math.PI);
                ctx.stroke();
            }
        }
        function move() {
            for(let i = 0, len = cells.length; i < len; i++) {

                cells[i].x += Math.random()*3;
                cells[i].x -= Math.random()*2;
                cells[i].y += Math.random()*3;
                cells[i].y -= Math.random()*2;
            }
        }
        function grow() {
            for(let i = 0, len = cells.length; i < len; i++) {
                if(cells[i].r > 10){
                    mitosis();
                }
                else {
                    cells[i].r+=0.25;
                }
            }
        }
        function mitosis() {
            for(let i = cells.length-1; i >= 0; i--) {
                cells.push(new Cell(cells[i].x,cells[i].y,5))
                cells.push(new Cell(cells[i].x,cells[i].y,5))
                cells.splice(i,1);
            }
        }
    </script>
    </body>
</html>

如果我对问题的理解正确,当你的大细胞即将分裂时,你可以创建并显示一个 "snapshots" 的列表,显示两个新细胞在开始前移动到它们的新位置又长出来了。

在那种情况下,如果你想/被允许使用 ES2017 功能,这是一个可能的解决方案,它使用真正的睡眠 - 暂停执行 - 而不是超时。 (我留给你创建你的快照列表和 displaySnapshot 函数,它擦除和绘制每个快照。这几乎是微不足道的)

  function sleep(ms) {
     return new Promise(resolve => setTimeout(resolve, ms));
  }
  async function displaySnapshots(snapshots, timeLapse) {
     for (let snap of snapshots) {
        displaySnapshot(snap);
        await sleep(timeLapse);
     }
 }

但不确定你是否想做这样的事情(我认为不是):

     function sleep(ms) {
         return new Promise(resolve => setTimeout(resolve, ms));
      }

      async function evolve(timeLapse, iterations) {
         for (let i = 0; i < iterations; i++) {
            update();
            await sleep(timeLapse);
         }
     }
     evolve(500, 100);