簡體   English   中英

在javascript中順時針旋轉,然后逆時針旋轉

[英]clockwise and then anticlockwise rotation in javascript

我想旋轉畫布元素以先按順時針方向旋轉動畫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); } 

旋轉()相對於其當前變換旋轉元素還是絕對旋轉? 而不是做

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

嘗試

    5*Math.PI / 180

為您的旋轉參數。 這樣旋轉將使它每次旋轉5度。 並使其向后退時為-5。 我猜到那時您將使用一個計數器來確定是否已通過180/5步,並使其有時間倒退。

您已經引入了flag3但我認為您不需要它。 我假設旋轉從ang = 0開始,並且flag2將告訴旋轉方向:false時遞增,true時遞減。 但是,當它為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,然后停止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM