在javascript中顺时针旋转然后逆时针旋转

时间:2014-11-07 13:52:46

标签: javascript canvas

我想旋转一个画布元素,首先按顺时针方向旋转180度旋转,然后进行180度的反向(逆时针)旋转。我使用了这段代码,但它不能正常工作。

 function Rotate(arg) {
                rotateInterval = setInterval(function () {
                    arg.save(); //saves the state of canvas
                    arg.clearRect(0, 0, arg.canvas.width, arg.canvas.height); //clear the canvas
                    arg.translate(arg.canvas.width / 2, arg.canvas.height / 2); //let's translate

                    if (flag2 == false)
                       arg.rotate(-(ang += 5) * Math.PI / 180); //increment the angle and rotate the image 
                        //arg.style.rotate(5);
                    else {
                        
                        ang = 0;
                        arg.rotate((ang += 5) * Math.PI / 180);
                       
                    }
                    if (ang == 180) {
                        if (flag2 == true)
                            flag3 = true;
                        else
                        flag2 = true;
                    }
                    if (flag3 == true && ang == 180) {
                        clearInterval(rotateInterval)
                        flag2 = false;
                    }
                    // ctxOne.drawImage(bowl, -ctxOne.canvas.width / 2, -ctxOne.canvas.height / 2, ctxOne.canvas.width, ctxOne.canvas.height); //draw the image ;)
                    arg.drawImage(bowl, -90, -90, 180, 180);
                    arg.restore(); //restore the state of canvas
                }, 100);
            }

2 个答案:

答案 0 :(得分:0)

rotate()是否相对于当前变换旋转元素,还是绝对旋转?而不是做

    (angle+=5)*Math.PI / 180

    5*Math.PI / 180

表示你的旋转参数。旋转方式每次旋转5度。当它倒退时,将它设为-5。我想在那时你会用一个计数器来确定是否已经过了180/5步并让它有时间倒退。

答案 1 :(得分:0)

您已经介绍了flag3,但我认为您并不需要它。我假设旋转以ang = 0开始,flag2将告诉旋转方向:false时递增,true时递减。但是当它成立时你总是设置ang = 0。您的代码应如下所示:

var rotateInterval, ang = 0, flag2 = false;

function Rotate(arg) {

rotateInterval = setInterval(function () {
    arg.save();
    arg.clearRect(0, 0, arg.canvas.width, arg.canvas.height);
    arg.translate(arg.canvas.width / 2, arg.canvas.height / 2);

    if (flag2 == false) ang += 5; // increment ang if flag2 == false ( = go forward)
    else ang -= 5; // otherwise decrement ang ( = go backwards)

    arg.rotate(ang * Math.PI / 180); // set the new ang to the rotation

    if (ang == 180) flag2 = true; // change direction if 180 deg is reached

    if (flag2 == true && ang == 0) { // if we go backwards and have reached 0 reset
        clearInterval(rotateInterval)
        flag2 = false;
    }

    arg.drawImage(bowl, -90, -90, 180, 180);
    arg.restore(); //restore the state of canvas
}, 100);

}

现在角度从0开始,逐步上升到180,然后逐步回到0,然后停止。