HTML5 canvas - rotate object without moving coordinates

前端 未结 2 1278
谎友^
谎友^ 2020-12-08 07:20

What I have is this: \"Tank\"

What I want is to rotate the red rectangle e.g. 20 degrees, but

2条回答
  •  甜味超标
    2020-12-08 07:52

    Sounds like you want to rotate the rect around its centerpoint.

    Red rectangle is original, Yellow rectangle is rotated around the centerpoint.

    enter image description here

    To do that you need to first context.translate to the rect's centerpoint before rotating.

    // move the rotation point to the center of the rect
    
        ctx.translate( x+width/2, y+height/2 );
    
    // rotate the rect
    
        ctx.rotate(degrees*Math.PI/180);
    

    Note that the context is now in its rotated state.

    That means drawing position [0,0] is visually at [ x+width/2, y+height/2 ].

    So you must draw the rotated rect at [ -width/2, -height/2 ] (not at the original unrotated x/y).

    // draw the rect on the transformed context
    // Note: after transforming [0,0] is visually [-width/2, -height/2]
    //       so the rect needs to be offset accordingly when drawn
    
        ctx.rect( -width/2, -height/2, width,height);
    

    Here is code and a Fiddle: http://jsfiddle.net/m1erickson/z4p3n/

    
    
    
     
    
    
    
    
    
    
    
    
    
        
    
    
    

提交回复
热议问题