Looping in a spiral

前端 未结 30 2679
独厮守ぢ
独厮守ぢ 2020-11-22 15:07

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fe

30条回答
  •  温柔的废话
    2020-11-22 15:33

    I made this one with a friend that adjusts the spiral to the canvas aspect ratio on Javascript. Best solution I got for a image evolution pixel by pixel, filling the entire image.

    Hope it helps some one.

    var width = 150;
    var height = 50;
    
    var x = -(width - height)/2;
    var y = 0;
    var dx = 1;
    var dy = 0;
    var x_limit = (width - height)/2;
    var y_limit = 0;
    var counter = 0;
    
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext('2d');
    
    setInterval(function(){
       if ((-width/2 < x && x <= width/2)  && (-height/2 < y && y <= height/2)) {
           console.log("[ " + x + " , " +  y + " ]");
           ctx.fillStyle = "#FF0000";
           ctx.fillRect(width/2 + x, height/2 - y,1,1);
       }
       if( dx > 0 ){//Dir right
           if(x > x_limit){
               dx = 0;
               dy = 1;
           }
       }
       else if( dy > 0 ){ //Dir up
           if(y > y_limit){
               dx = -1;
               dy = 0;
           }
       }
       else if(dx < 0){ //Dir left
           if(x < (-1 * x_limit)){
               dx = 0;
               dy = -1;
           }
       }
       else if(dy < 0) { //Dir down
           if(y < (-1 * y_limit)){
               dx = 1;
               dy = 0;
               x_limit += 1;
               y_limit += 1;
           }
       }
       counter += 1;
       //alert (counter);
       x += dx;
       y += dy;      
    }, 1);
    

    You can see it working on http://jsfiddle.net/hitbyatruck/c4Kd6/ . Just be sure to change the width and height of the canvas on the javascript vars and on the attributes on the HTML.

提交回复
热议问题