canvas裏面的transfrom與css3中的基本是一樣的,唯一的不同是原點,canvas的默認原點是圖形的左上角,css3是圖形的中心,
translate(x,y)方法
是用來移動canvas和它的原點到一個不同的位置,在做變形前,先保存狀態是一個良好的習慣,
transform的例子
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
ctx.save();
ctx.fillStyle = 'rgb(' + (51 * i) + ', ' + (255 - 51 * i) + ', 255)';
ctx.translate(10 + j * 50, 10 + i * 50);
ctx.fillRect(0, 0, 25, 25);
ctx.restore();
}
}
}
旋轉rotate(angle)
旋轉的中心點始終是 canvas 的原點,如果要改變它,我們需要用到 translate 方法。
這個方法只接受一個參數:旋轉的角度(angle),它是順時針方向的,以弧度爲單位的值。
rotate(angle)的例子
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.translate(75,75);
for (var i=1;i<6;i++){ // Loop through rings (from inside to out)
ctx.save();
ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)';
for (var j=0;j<i*6;j++){ // draw individual dots
ctx.rotate(Math.PI*2/(i*6));
ctx.beginPath();
ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
ctx.fill();
}
ctx.restore();
}
}
縮放scale(x, y)
我們用它來增減圖形在 canvas 中的像素數目,對形狀,位圖進行縮小或者放大。
方法接受兩個參數。x,y 分別是橫軸和縱軸的縮放因子,它們都必須是正值。值比 1.0 小表示縮小,比 1.0 大則表示放大,值爲 1.0 時什麼效果都沒有。
變形 Transform
ctx.transform(a, b, c, d, e, f),上面的3種方法都是基於transform的,也就是transform的快捷方式
這個函數的參數各自代表如下:
a:水平方向的縮放
b:水平方向的傾斜偏移
c:豎直方向的傾斜偏移
d:豎直方向的縮放
e:水平方向的移動
f:豎直方向的移動
- 縮放:scale(a, d) 等同於 matrix(a, 0, 0, d, 0, 0);
- 平移:translate(e, f) 等同於 matrix(1, 0, 0, 1, e, f);
- 旋轉:rotate(deg) 等同於 matrix(cos(deg), sin(deg), -sin(deg), cos(deg), 0, 0);
一個圖形同時需要縮放平移和旋轉,就是3個單獨的矩陣相乘
舉例 transform:translate(10px,20px) rotate(37deg) scale(1.5,2)
即 matrix(1.2,0.9,-1.2,1.6,10,20)
上面的3個矩陣可以先計算2個相乘,得出的結果與第三個相乘
矩陣的算法對應關係(如下圖)
resetTransform() 重置當前變形爲單位矩陣,它和調用以下語句是一樣的:ctx.setTransform(1, 0, 0, 1, 0, 0);
transform與setTransform的例子
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var sin = Math.sin(Math.PI/6);
var cos = Math.cos(Math.PI/6);
ctx.translate(100, 100);
var c = 0;
for (var i=0; i <= 12; i++) {
c = Math.floor(255 / 12 * i);
ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
ctx.fillRect(0, 0, 100, 10);
ctx.transform(cos, sin, -sin, cos, 0, 0);
}
ctx.setTransform(-1, 0, 0, 1, 100, 100);
ctx.fillStyle = "rgba(255, 128, 255, 0.5)";
ctx.fillRect(0, 50, 100, 100);
}
上面的代碼ctx.setTransform(-1, 0, 0, 1, 100, 100);是什麼意思?先明白ctx.setTransform(-1, 0, 0, 1,0, 0);的意思,看下面的圖示就很明白
公衆號:前端之攻略