キャンバスを画像のサイズに合わせて小さな画像に調整するコードサンプルがあります。キャンバスのサイズを調整するキャンバス内部の画像を回転させる右回転機能があります。私はほとんど完全にそれを働いているが、イメージはオリジナルまたは逆さまのときにのみ完璧なサイズです。画像を左または右に回転させると、高さを適切な比率にすることができません。ここで私のjsfiddleとコードは、異なるフィドルから変更されたコードです。画像はテストとして使用されます。Html canvas画像をアスペクト比で回転する
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasWidth = 400;
var canvasHeight;
var degrees=0;
var image=document.createElement("img");
image.onload=function(){
canvas.width = canvasWidth;
canvasHeight = 400/(image.width/image.height);
canvas.height = canvasHeight;
ctx.drawImage(image,0,0,canvas.width,canvas.height);
}
image.src="https://www.magezinepublishing.com/equipment/images/equipment/Lumix-DMCFZ330-5824/highres/Panasonic-Lumix-FZ330-Wide-P1010001_1438873612.jpg";
$("#clockwise").click(function(){
degrees+=90
if (degrees >= 360) degrees = 0;
if (degrees === 0 || degrees === 180) {
canvas.width = canvasWidth;
canvas.height = canvasHeight;
}
else {
// swap
canvas.width = canvasHeight;
canvas.height = canvasWidth;
}
ctx.save();
// you want to rotate around center of canvas
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image, -canvas.width*0.5, -canvas.height*0.5, canvas.width, canvas.height);
ctx.restore();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" ></canvas><br>
<button id="clockwise">Rotate right</button>
すべてのヘルプは高く評価されます。
イメージを回転させようとしているだけの場合は、キャンバスは必要ありません。プレーンなCSSで十分です。 – Nisarg
回転は単なるものなのでキャンバスが必要です。私は新しいイメージを作成するためにキャンバスに他の要素を追加する他のロジックを持っています。 – Jim