I am struggling to create line drawing animation using request animation frame. While I was using setInterval function everything was working fine, but I read somewhere that request ani frame is much more optimized and that all functions in interval should be written in this manner.

So here is my code:

var topMinX = 3; var topMaxX = 75; var topMinY = 2;
var topMaxY = 2; var min; var max;

//request animation frame
   (function animate(){
        var t = setTimeout(function(){
            requestAnimFrame(animate);
            var d = render(topMinX,topMaxX,topMinY,topMaxY,true);
        },20);

    })();

     function render(xMin,xMax,yMin,yMax,direction){
        if(direction){
            min = xMin;
            max = xMax
         }else{
            min = yMin;
            max = yMax;
         }      

        if(min<max){
             context.beginPath();
             if(direction){
                context.moveTo(xMin,yMin);
                xMin = xMin+2;
                alert(xMin);
                context.lineTo(xMin,yMax);
             }else{
                context.moveTo(xMin,yMin);
                yMin = yMin+2;
                context.lineTo(xMax,yMin);
             }                   
             context.lineWidth = 4;
             context.stroke();              
        }

     }  

The problem is that xMin value won't increment. It will always alert 5 and I expected it to increment by 2 in every iteration. Basically I just want to draw a square, so I don't need any diagonal moves, that's why I've added the direction parameter.

I am new to canvas and request ani frame, so any help would be more then useful.

有帮助吗?

解决方案

I don't know about square drawing, but the problem here seems to be in variable passing to function.

Those variables you have defined at the beginning does not get changed when passing furher into functions

You can check how it works here:

function swap(a, b) {
   var tmp = a;
   a = b;
   b = tmp; //assign tmp to b
}

var x = 1, y = 2;
swap(x, y);

alert("x is " + x + " y is " + y); // "x is 1 y is 2"

And your example on FIDDLE

it does draw a line and topMinX is incremented

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top