javascript - 使用 Canvas 在 Javascript 中制作动画

标签 javascript canvas

我正在尝试使用更新渲染动画循环在 Canvas 上实现冒泡排序动画。

如果以下是冒泡排序的实际非动画版本

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 不支持任何 sleep 功能,我无法简单地将上面的代码转换为如下所示的动画版本

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
});

最佳答案

如果您可以使用 setTimeout 重写循环来触发每次迭代,那么浏览器就有时间在每次迭代之间重绘。所以也许是这样的:

function doIteration(i,j,max,callback) {
   callback(i,j);
   if (++j >= max){
     j = 0;
     i++;
   }
   if (i < max)
      setTimeout(function() { doIteration(i,j,max,callback); }, 100);
}

var arr = [12, 3, 4, 1, 20, 2, 5, 7, 9, 13, 19, 6, 8, 14, 18, 10, 15, 11, 16, 17];

function drawFunction() {
   document.getElementById("output").innerHTML = arr.join(",") + "<br>";   
}

doIteration(0,0,arr.length-1,function(i,j){
   var t;
   if(arr[j] > arr[j+1]) {
      t = arr[j];
      arr[j] = arr[j+1];
      arr[j+1] = t; 
   }
   drawFunction();
});

使用 i 和 j 的起始值以及最大值(在本例中它们都有相同的最大值,因此我将其保留为单个参数)和回调函数调用 doIteration将在每次迭代时调用并传递当前的 i 和 j。确实应该在第一次调用回调之前测试 i 和 j 的值,但我会将其作为读者的练习。

这是一个简化了绘制过程的演示:http://jsfiddle.net/Kpkxw/2/

我猜你已经朝着这个方向前进了,但我发现你的迭代分布在多个函数中的方式有​​点令人困惑,我更喜欢将其放在一个函数中。

注意:这是一种不可靠的实现,只是我凭空想象出来的,所以我没有时间按比例构建它或绘制它......

关于javascript - 使用 Canvas 在 Javascript 中制作动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8615204/

相关文章:

javascript - Google Chrome 中的 MouseUp 和 MouseDown 事件

javascript - Canvas HTML 加载时间

android - ScrollView 及其 subview 如何控制滚动

javascript - 在 JavaScript 中使用 $_SESSION ["attribute"]

javascript - RJS:Ajaxified select_tag

javascript - 只需要得到小数点后两位数

html - 修改 “ALIEN Deviation” 笔 - - HTML Canvas 问题

javascript - 如何在缩放时重新定位固定控件

c# - 如何在 Asp.Net 的服务器端使用 JavaScript 对象?

javascript - 如何平滑我的 JavaScript 动画?