canvas:如何在一个变换语句中完成平移、倾斜、旋转...?

2024-05-05

最近几天我在学习“变换”,现在我知道如何通过变换的矩阵进行平移、旋转、倾斜、缩放。但如果我想在一个转换语句中执行上述所有操作,我该怎么办?

ctx.transform(a,b,c,d,e,f);

当我们想要通过变换旋转某些东西时,我们必须为每个参数传递4个参数(a,b,c,d),所以,如果我想要旋转和缩放,例如旋转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;   
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

canvas:如何在一个变换语句中完成平移、倾斜、旋转...? 的相关文章

随机推荐