Html5 Canvas Transformation Algorithm - Finding object coordinates after applying transformation

前端 未结 2 564
名媛妹妹
名媛妹妹 2021-01-01 07:43

On html5 canvas I am drawing objects (rectangle, circle, etc...), these objects have transformation properties like scale, skew, rotation etc... These objects can be nested.

相关标签:
2条回答
  • 2021-01-01 07:57

    All affine transformations in 2D can be expressed as a matrix of the form:

        [ a  c  dx ]
    T = [ b  d  dy ]
        [ 0  0   1 ]
    

    This could be expressed with the method context.transform(a, b, c, d, dx, dy);.

    When applied to some coordinate, (x,y), you first have to add a third coordinate, which is always 1: <x, y, 1>. Then you can multiply the transformation matrix to get the result:

    [ a*x + c*y + dx ]
    [ b*x + d*y + dy ]
    [       1        ]
    

    If you get anything other than '1' in the last coordinate, you have to divide the vector by it.


    To go the other way, you have to invert the matrix:

    [ d/M  -c/M  (c*dy - d*dx)/M ]
    [ b/M   a/M  (b*dx - a*dy)/M ]
    [  0     0          1        ]
    

    where M is (a*d - b*c).


    Multiple transformations could be applied in sequence, by multiplying their matrices. The order of the multiplications are important.


    context.translate(dx,dy) <==> context.transform( 1,  0,  0,  1, dx, dy)
    context.rotate(θ)        <==> context.transform( c,  s, -s,  c,  0,  0)
    context.scale(sx,sy)     <==> context.transform(sx,  0,  0, sy,  0,  0)
    

    where c = Math.cos(θ) and s = Math.sin(θ)


    If you got some coordinate (x,y) in object-space, and you want to know where it will end up on the screen, you apply the transformation to it.

    If you got some coordinate (x,y) on the screen, and you want to know which point on the object that is, you multiply by the inverse of the transformation.

    0 讨论(0)
  • 2021-01-01 08:00

    Tom Larkworthy's answer is perfect, but with a minor typo. Correct formula to invert the matrix is:

    [  d/M  -c/M  (c*dy - d*dx)/M ]
    [ -b/M   a/M  (b*dx - a*dy)/M ]
    [   0     0          1        ]
    
    0 讨论(0)
提交回复
热议问题