Matrix 3x3 ควบคุมการ Transform ทั้งหมด
Canvas เก็บ Current Transformation Matrix (CTM) เริ่มต้นเป็น Identity Matrix
Matrix Format
[ m11 m21 dx ]
[ m12 m22 dy ]
[ 0 0 1 ]
m11, m22- Scale X, Ym12, m21- Skew/Sheardx, dy- Translate X, Y
เมธอดหลัก
transform(a, b, c, d, e, f)- คูณ CTM × Matrix ใหม่ (m11=a, m12=b, m21=c, m22=d, dx=e, dy=f)setTransform(a, b, c, d, e, f)- รีเซ็ต CTM = Identity แล้ว Apply MatrixresetTransform()- รีเซ็ตเป็น Identity (Modern Browsers)
ตัวอย่าง: หมุนและ Translate
ctx.translate(200, 200); // dx=200, dy=200
var sin = Math.sin(Math.PI/6), cos = Math.cos(Math.PI/6);
ctx.transform(cos, sin, -sin, cos, 0, 0); // หมุน 30 องศา
ctx.setTransform(-1, 0, 0, 1, 200, 200); // Flip X แล้ว Translate
เข้าใจ Matrix ช่วยคำนวณ Transform ซับซ้อนได้แม่นยำ