我想在使用更新渲染動畫循環的畫布上實現氣泡排序動畫。使用畫布的Javascript中的動畫
因此,如果下面是泡沫的實際非動畫版的排序
for(var i = 0 ;i < arr.length - 1; i++)
for(var j = 0 ;j < arr.length - 1; j++)
if(arr[j] > arr[j+1]) { swap arr[j], arr[j+1]}
我的要求現在的問題是,在每一個交換或比較指令,所有的酒吧(數組元素)應該被重新繪製。但由於多年平均值的JavaScript支持任何睡眠功能,我不能簡單地轉換上面的代碼動畫版如下圖所示
for(var i = 0 ;i < arr.length - 1; i++)
for(var j = 0 ;j < arr.length - 1; j++){
if(arr[j] > arr[j+1]) { after swap..... }
call to draw method // draw all bars
sleep(); // doesnot work in javascript
}
天色我能夠使用setTimeout函數來實現它。但我無法弄清楚,我們怎樣才能將嵌套循環內部的代碼(比較和交換)完全摺疊成單獨的函數(更新函數),而不會丟失索引變量的狀態。
所以,請讓我知道是否有任何優雅的解決方案的問題 下面是我的實現通過展開循環到單獨的函數。當然,如果算法包含更緊密的環路,我的實現不會擴展。
$(function(){
var canvas = $("#mycan");
var ctx = canvas.get(0).getContext("2d");
(function Graph(nBars,ctx){
this.nBars = nBars;
this.Bars = [];
var MaxBarLen = 250;
function Bar(color,height,x,y){
this.color = color;
this.height = height;
this.width = 10;
this.x = x;
this.y = y;
};
Bar.prototype.toString = function(){
return "height: "+height+" x: "+x+" y: "+y;
};
function init(){
//create bars randomly of size 10 - 250
for(var i = 0;i < nBars; i++){
Bars.push(new Bar("rgb(0,0,0)", Math.floor(Math.random()*MaxBarLen+10),15*i+1,MaxBarLen))
}
algo();
//draw();
};
//method to draw the bars collection to the given context
this.draw = function(){
ctx.clearRect(0,0,500,500);
for(var i = 0; i < nBars; i++){
if(Bars[i].color == "rgb(0,0,0)")
ctx.fillRect(Bars[i].x,Bars[i].y,Bars[i].width,-Bars[i].height);
else{
ctx.fillStyle = Bars[i].color;
ctx.fillRect(Bars[i].x,Bars[i].y,Bars[i].width,-Bars[i].height);
ctx.fillStyle = "rgb(0,0,0)";
}
}
};
// BUBBLE SORT ALGORITHM
var I = -1, J = -1;
this.algo = function(){
updateI(); // invocate outer loop
};
//outer loop
var updateI = function(){
console.log("updateI", I, J);
if(I < Bars.length - 1){
J = -1;
I++;
updateJ();
}
};
//inner loop
var updateJ = function(){
console.log("updateJ", I, J);
if(J < Bars.length - 2){
J++;
setTimeout(compare,100); // trigger the compare and swap after very 100 ms
}else{
updateI();
}
};
//actual compare function
var compare = function(){
console.log("compare ", I, J);
Bars[J].color = "rgb(0,255,0)";
Bars[J+1].color = "rgb(0,0,255)";
draw(); //draw the frame.
if(Bars[J].height > Bars[J+1].height){
//update
temp = Bars[J].height;
Bars[J].height = Bars[J+1].height;
Bars[J+1].height = temp;
}
Bars[J].color = Bars[J+1].color = "rgb(0,0,0)";
updateJ(); //render next iteration
};
//invoke bar creation and bubble sort algorithm
init();
})(10,ctx); // 10 bars and context
});