方法canvas
save() 保存canvas狀態 restore() 回覆canvas保存的狀態 translate(x, y) 移動canvas位置 rotate(radians) 順時針方向旋轉canvas,弧度 = (Math.PI/180)*角度) scale(x, y) 縮放座標軸,若是是負數則座標軸反向
移動畫布動畫
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.save(); ctx.fillStyle='orange'; ctx.translate(10, 10); ctx.fillRect(0,0, 10, 10) ctx.restore(); ctx.save(); ctx.fillStyle='red'; ctx.translate(20, 20); ctx.fillRect(0,0, 10, 10); ctx.restore(); ctx.save(); ctx.fillStyle='blue'; ctx.translate(30, 30); ctx.fillRect(0,0, 10, 10); ctx.restore(); ctx.save(); ctx.fillStyle='green'; ctx.translate(40, 40); ctx.fillRect(0,0, 10, 10);
旋轉畫布rest
ctx.fillStyle='orange'; ctx.translate(200, 200); for(var i = 1; i <= 18; i++){ ctx.rotate((Math.PI / 180) * 20 * i); ctx.fillRect(0, 0, 100, 100); }
縮放座標軸code
ctx.fillStyle='orange'; ctx.font = '30px serif'; ctx.translate(200, 100); ctx.scale(-1, 1); ctx.fillText('Hello world', 10, 50);