2017-01-20 7 views
0

私はキャンバスで回転するハンドルを取得しようとしていますが、私は私の問題の答えが見つかりませんでした。HTML 5キャンバス。 1つのオブジェクト(> 1)だけを回転(回転を維持)する方法?

1つの正方形はまだ残っています。指定された点で回転する別の正方形。その時点でキャンバス全体を回転させるか、まったく回転させないかのどちらかです。しかし、1つの正方形を静的に、1つを回転させることはできません。

ここに私のcodepenデモをご覧ください:http://codepen.io/richardk70/pen/EZWMXx

のjavascript:

HEIGHT = 400; 
WIDTH = 400; 

function draw(){ 

var ctx = document.getElementById("canvas").getContext('2d'); 
ctx.clearRect(0,0,WIDTH,HEIGHT); 

// draw black square 
ctx.save(); 
ctx.fillStyle = "black"; 
ctx.beginPath(); 
ctx.fillRect(75,75,100,100); 
ctx.closePath(); 
ctx.restore(); 

// attempt to rotate small, maroon square only 
ctx.save(); 
ctx.translate(225,225); 

// small maroon square 
ctx.fillStyle = "maroon"; 
ctx.beginPath(); 
ctx.fillRect(-25,-25,50,50); 
ctx.closePath(); 
ctx.rotate(.1); 
ctx.translate(-225,-225); 

// comment out below line to spin 
// ctx.restore(); 

window.requestAnimationFrame(draw); 
} 

window.requestAnimationFrame(draw); 

を私は層状のキャンバスを行うことができます知っているが、確かにそれはちょうど1つの帆布層で行うことができますか?このチュートリアル(https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations)の時計は正確にそれをしていませんか?

ありがとうございました。

+0

あなたがリンクの例を見れば、それはので、各描画呼び出しがわずかに惑星をシフトし、現在の時刻に基づいて回転量を調整します。コンテキスト内でローテーションを蓄積しようとしていますが、それはどのように動作しているのではありません。 – DrC

答えて

0

イメージを1つだけ回転するか、またはキャンバスの変換状態をデフォルトに戻す必要があります。

この関数は、オブジェクトを回転して回転させてレンダリングしますが、他のレンダリングには影響しません。

ところであなたは、レンダリング呼び出しは、このようなctx.fillRectctx.strokeRectctx.fillTextctx.strokeTextとして塗りまたは線で始まり、あなただけは、最後のパスポイントからラインを作成する必要がある場合はctx.closePathを使用する必要がありますさにbeginPathを使用する必要はありませんctx.beginPathの後の先のctx.moveToポイントまたは最初のパスポイント

また、すべてのレンダリングで保存と復元を使用する必要はありません。以前のキャンバスの状態を戻す必要がある場合にのみ使用します。

ctx = canvas.getContext("2d"); 
 

 
function drawBox(col,size,x,y,scale,rot){ 
 
    ctx.fillStyle = col; 
 
    // use setTransform as it overwrites the canvas transform rather than multiply it as the other transform functions do 
 
    ctx.setTransform(scale, 0, 0, scale, x, y); 
 
    ctx.rotate(rot); 
 
    ctx.fillRect(-size/2,-size/2, size, size); 
 
} 
 

 

 
function update(time){ 
 
    ctx.clearRect(0,0,512,256) 
 
    drawBox("black",100,125,125,1,0); // draw none rotated box 
 
    drawBox("maroon",50,225,125,1,time/500); // draw rotating box 
 
    drawBox("green",25,275,100,1,-time/250); // draw rotating box 
 
    drawBox("green",25,275,150,1,-time/250); // draw rotating box 
 
    // after using transforms you need to reset the transform to the default 
 
    // if you plan to render anything in the default coordinate system 
 
    ctx.setTransform(1, 0 ,0 , 1, 0, 0); // reset to default transform 
 

 
    requestAnimationFrame(update); 
 
} 
 

 
requestAnimationFrame(update);
<canvas id="canvas" width="512" height="256"></canvas>

+0

Blindman、私は「感謝」と言うべきではないと思っていますが、私は驚いています。サンプルソリューションを使用していただきありがとうございます。本当にありがとう。 – Richard

関連する問題