我有一個代碼示例,我正在將大圖調整爲較小的大小,畫布與圖像大小相匹配。有一個旋轉右鍵功能,可以旋轉畫布內部的圖像,以調整畫布大小。我幾乎擁有完美的工作,但只有在原創或顛倒的情況下,圖像纔是完美的尺寸。當圖像左右旋轉時,我無法將高度設置爲正確的比例。這是我的jsfiddle和從不同的小提琴修改代碼的代碼。圖像僅用作測試。Html畫布旋轉放大圖像的縱橫比
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