【发布时间】:2018-01-23 02:18:21
【问题描述】:
我正在制作一个有丝分裂模拟器,我希望它在细胞足够大并分裂时运行有丝分裂功能。当它拆分时,我希望它动画从初始 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>
【问题讨论】:
标签: javascript arrays animation simulation