最近在研究'transform',现在我知道如何通过transform的matirx进行平移,旋转,倾斜,缩放。但是如果我想在一个转换语句中执行上述所有操作,我该怎么做?
ctx.transform(a,b,c,d,e,f);
当我们想要通过变换旋转某些东西时,我们必须为每个参数(a、b、c、d)传递 4 个参数,所以,如果我想要旋转和缩放,例如,旋转 30 度并缩放(1.5,2 ), 变换可以同时完成吗?那么 (a,b,c,d) 的值是多少?以及如何计算它们?
还有一个问题:transform有顺序吗?我的意思是,如果我使用变换来旋转、缩放和平移,它们之间的顺序是什么?毕竟,顺序很重要,“先翻译,再缩放”和“先缩放,再翻译”,会得到不同的结果。
最佳答案
这是由 context.transform(a,b,c,d,e,f) 完成的数学运算
当您使用单个 context.transform 进行多个操作时(平移+缩放+旋转)
- 首先完成翻译。
- 接下来进行缩放和旋转(顺序无关紧要)。
这是 javascript 形式的矩阵数学:
// a=0, b=1, c=2, d=3, e=4, f=5
// declare an array that will hold our transform math
// this is the identity matrix (where no transforms exist)
var matrix=[1,0,0,1,0,0];
// for example,
// rotate 30 degrees clockwise from 0 degrees
// note: 0 degrees extends rightward horizontally from the origin
rotate(30*Math.PI/180);
// scale by 1.5 in X and 2.0 in Y scales
scale(1.5,2,0);
// plug our transform array into the context
context.transform(matrix[0],matrix[1],matrix[2],matrix[3],matrix[4],matrix[5]);
// do the translate to the array
function translate(x,y){
matrix[4] += matrix[0] * x + matrix[2] * y;
matrix[5] += matrix[1] * x + matrix[3] * y;
}
// do the scale to the array
function scale(x,y){
matrix[0] *= x;
matrix[1] *= x;
matrix[2] *= y;
matrix[3] *= y;
}
// do the rotate to the array
function rotate(radians){
var cos = Math.cos(radians);
var sin = Math.sin(radians);
var m11 = matrix[0] * cos + matrix[2] * sin;
var m12 = matrix[1] * cos + matrix[3] * sin;
var m21 = -matrix[0] * sin + matrix[2] * cos;
var m22 = -matrix[1] * sin + matrix[3] * cos;
matrix[0] = m11;
matrix[1] = m12;
matrix[2] = m21;
matrix[3] = m22;
}
关于javascript - canvas: 如何在一个转换语句中完成平移、倾斜、旋转...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18437039/