4

キャンバスがあるとします:

<canvas id="one" width="100" height="200"></canvas>

ボタンをクリックすると、キャンバスが時計回りに (中心を中心に) 90 度回転し、キャンバスの寸法も更新されます。

<canvas id="one" width="200" height="100"></canvas>

キャンバスの id は同じであることに注意してください。

トリミングやパディングを行わずに、単純に画像を時計回りに回転させることを想像してみてください。

新しいキャンバスを作成し、ピクセルごとに回転およびコピーする長い道のりを行う前に、何か提案はありますか?

コメントからの提案でサンプルコードを更新しても機能しません:

function imageRotatecw90(){

    var canvas = document.getElementById("one");
    var context = canvas.getContext("2d");

    var cw=canvas.width;
    var ch=canvas.height;

    var myImageData = context.getImageData(0,0, cw,ch);

    context.save();

    context.translate(cw / 2, ch / 2);
    context.rotate(Math.PI/2);

    context.putImageData(myImageData, 0, 0);

    context.restore();

    canvas.width=ch;
    canvas.height=cw;
}

FiddleJS

4

2 に答える 2

9

このDEMOを見てください。

デモで見た結果を得るためにcanvas.toDataURL、キャンバスを画像にキャッシュし、キャンバスを新しい寸法にリセットし、コンテキストを適切に変換および回転し、最後にキャッシュされた画像を変更されたキャンバスに戻します。

そうすれば、すべてを再描画する必要なく、キャンバスを簡単に回転できます。ただし、anti-aliasingメソッドはブラウザで使用されるため、この操作を実行するたびに、結果がぼやけていることに気付くでしょう。この動作が気に入らない場合、私が理解できる唯一の解決策は、すべてを再度描画することですが、追跡がはるかに困難です。

コードは次のとおりです。

var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;

// Sample graphic
context.beginPath();
context.rect(10, 10, 20, 50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();

// create button
var button = document.getElementById("rotate");
button.onclick = function () {
    // rotate the canvas 90 degrees each time the button is pressed
    rotate();
}

var myImageData, rotating = false;   

var rotate = function () {
    if (!rotating) {
        rotating = true;            
        // store current data to an image
        myImageData = new Image();
        myImageData.src = canvas.toDataURL();

       myImageData.onload = function () {
            // reset the canvas with new dimensions
            canvas.width = ch;
            canvas.height = cw;
            cw = canvas.width;
            ch = canvas.height;

            context.save();
            // translate and rotate
            context.translate(cw, ch / cw);
            context.rotate(Math.PI / 2);
            // draw the previows image, now rotated
            context.drawImage(myImageData, 0, 0);               
            context.restore();

            // clear the temporary image
            myImageData = null;

            rotating = false;               
        }
    }
}
于 2013-05-20T14:04:23.920 に答える