function toChange() {
switch(iNow) {
case 1:
oC.width = obj.height; oC.height = obj.width;
oGC.rotate(90*Math.PI/180);
oGC.drawImage(obj, 0, -obj.height);
break;
}
}
點擊按鈕 `iNow++` 觸發 `toChange()`,但畫布無變化。
function drawRotated(img, angle) {
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 1. 計算旋轉後尺寸
const rad = angle * Math.PI / 180;
const sin = Math.abs(Math.sin(rad)), cos = Math.abs(Math.cos(rad));
const newW = img.width * cos + img.height * sin;
const newH = img.width * sin + img.height * cos;
canvas.width = newW; canvas.height = newH; // 重置變換
// 2. 平移到中心
ctx.translate(newW/2, newH/2);
// 3. 旋轉
ctx.rotate(rad);
// 4. 繪製(以圖片中心為原點)
ctx.drawImage(img, -img.width/2, -img.height/2);
}
let angle = 0;
document.getElementById('btnRight').onclick = () => {
angle = (angle + 90) % 360;
drawRotated(imageObj, angle);
};