2017-03-14 15 views
0

ジェネリックキャンバスの描画を処理するためのJavaScriptコンポーネントをいくつか作成しています。回転を有効にするのに苦労しています。私はこれに似た関数を持っています(これはかなり単純化されています)。JavaScriptキャンバスで回転するジェネリック関数を作成するにはどうすればよいですか?

function drawThing (ctx, posX, posY, sizeX, sizeY, rotation, drawFn) { 
    // `ctx` is the 2d canvas context 
    ctx.save(); 
    ctx.beginPath(); // Not sure if this is needed 
    ctx.translate(posX, posY); // What do I use here? 
    ctx.rotate(rotation); // rotation is in radians 
    drawFn(ctx, posX, posY, sizeX, sizeY); 
    ctx.restore(); 
} 
function exampleDrawFn (ctx, posX, posY, sizeX, sizeY) { 
    ctx.fillStyle = "#333"; 
    ctx.fillRect((posX - sizeX/2), (posY - sizeY/2), sizeX, sizeY); 
} 

変換パラメータに何を使用するのかわかりません。どこか別のエラーがあるかもしれません。

(それは少し複雑ですが、ここで私が実際に働いているコードです:https://github.com/rocket-boots/rocket-boots/blob/master/scripts/rocketboots/Stage.js#L423)は

答えて

0

私は回転後の翻訳を逆転させるが、これを修正することができました。

この方法を改善する余地がある場合は不思議ですが、これはうまくいくはずです。

1

画像を描く最も速い方法です。画像をレンダリングが完了したら

function drawImage (image, x, y, sizeX, sizeY, rot) { 
    var xdx = Math.cos(rot); // direction of x axis 
    var xdy = Math.sin(rot); 
    ctx.setTransform(
     xdx, xdy, // set the direction of the x axis 
     -xdy, xdx, // set the direction of the y axis (at 90 deg clockwise from x axis 
     x, y  // set the origin the point around which to rotate 
    ); 
    ctx.drawImage(image,- sizeX/2, -sizeY/2, sizeX, sizeY); 
} 

あなたは点xであり、その中心の周りを回転画像をしたいと仮定すると、yは、あなたは...

これはよりちょうど速くある ctx.setTransform(1,0,0,1,0,0);

に変換デフォルトにリセットすることができます

function drawImage(image, x, y, sizeX, sizeY, rot){ 
    ctx.setTransform(1, 0, 0, 1, x, y); 
    ctx.rotate(rot); 
    ctx.drawImage(image, -sizeX/2, -sizeY/2, sizeX, sizeY); 
} 

... FFとChromeですが、それは明日ではないかもしれません。

+0

'ctx.drawImage'メソッドの入力ミスです:' -sizeX/2'と 'setTransform(...)'} '' – Kaiido

+1

@Kaiidoおかげさまで、私は眠る必要があると思います。 – Blindman67

+0

残念なことに、これを実装しようとすると、動作しませんでした/私の関数とまったく同じことをしませんでした。 – Luke

関連する問題