HTML5 Canvas Transformation Matrix

前端 未结 4 2103
悲&欢浪女
悲&欢浪女 2020-12-24 14:19

I don\'t understand what the Transformation Matrix is and how to work with it.

The following will draw a circle at 0, 0 of my canvas: (generated from an svg conv

4条回答
  •  礼貌的吻别
    2020-12-24 15:17

    The transformation matrix gets multiplied by each point before it's drawn on the canvas. Like @Eric said, it's an affine transformation matrix from linear algebra. In your example, it would work like this:

    [ x']   [ 1 0 -551.23701 ] [ x ]   [ x - 551.23701 ]
    [ y'] = [ 0 1 -368.42499 ] [ y ] = [ y - 368.42499 ]
    [ 1 ]   [ 0 0    1       ] [ 1 ]   [       1       ]
    

    So it shifts the x and y coordinates by -551.23... and -368.42... respectively.

    Other types of transformations involve different "slots" in the matrix. For example, here's the matrix that scales the drawing by sx and sy (x and y scaling factors):

    [ sx  0 0 ]
    [  0 sy 0 ]
    [  0  0 1 ]
    

    and rotation (angle is in radians):

    [ cos(angle) -sin(angle) 0 ]
    [ sin(angle)  cos(angle) 0 ]
    [     0           0      1 ]
    

    The advantage of using a transformation matrix over calling individual methods, like translate, scale, and rotate, is that you can perform all the transformations in one step. It gets complicated though when you start combining them in non-trivial ways because you need to multiply the matrices together to get the final result (this is what functions like scale, etc. are doing for you). It's almost always easier to call each function instead of calculating it yourself.

    The links @Eric mentioned and the transformation matrix article on Wikipedia go into a lot more detail about how it all works.

提交回复
热议问题