Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

HTML5 Canvas Transformation Matrix

Matrix Transformation Methods

Canvas มี 2 เมธอดหลักสำหรับจัดการ Transformation Matrix:

  • transform(m11, m12, m21, m22, dx, dy) - คูณ Matrix ปัจจุบันด้วย Matrix ใหม่
  • setTransform(m11, m12, m21, m22, dx, dy) - รีเซ็ตเป็น Identity แล้ว Apply Matrix ใหม่

Matrix Format (3x3)

[ m11  m21  dx ]
[ m12  m22  dy ]
[  0    0   1  ]

ตัวอย่าง: หมุนและวาดสี่เหลี่ยมซ้อนกัน

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
ctx.translate(200, 200); // ย้ายจุดกำเนิดไปกึ่งกลาง

var sin = Math.sin(Math.PI/6); // 30 deg
var cos = Math.cos(Math.PI/6);

for (var i = 0; i <= 12; i++) {
    var c = Math.floor(255 / 12 * i);
    ctx.fillStyle = 'rgb(' + c + ',' + c + ',' + c + ')';
    ctx.fillRect(0, 0, 100, 100);
    ctx.transform(cos, sin, -sin, cos, 0, 0); // หมุน 30 องศา
}

// รีเซ็ตและวาดสี่เหลี่ยมสีน้ำเงินโปร่งแสง
ctx.setTransform(-1, 0, 0, 1, 200, 200);
ctx.fillStyle = 'rgba(100, 100, 255, 0.5)';
ctx.fillRect(50, 50, 100, 100);