Home > other >  How do I get the new center point and the centered rotation angle after rotating a polygon around an
How do I get the new center point and the centered rotation angle after rotating a polygon around an

Time:08-07

I have a class that stores vertices for drawing onto an HTML5 canvas. The vertices are relative the the center point (0, 0).

x_pos: number
y_pos: number
vertices: [x: number, y: number][]
...
draw(ctx: CanvasRenderingContext2D): void {
    let verts = this.getRotatedVertices()
    console.log(this.rotation)
    this.applyStyle(ctx)
    ctx.beginPath()
    for(let i=0; i<verts.length; i  ) {
        ctx.lineTo(this.x_pos   verts[i][0], this.y_pos   verts[i][1])
    }
    ctx.closePath()
    ctx.stroke()
    ctx.fill()
}

It uses the following function to perform a rotation about an anchor point:

getRotatedVertices(angle: number, anchor_x: number, anchor_y: number): [x: number, y: number][] {
    let new_vertices: [x: number, y: number][] = []

    this.vertices.forEach((vert: [x: number, y:number]) => {
        let newX = anchor_x   (vert[0]-anchor_x)*Math.cos(angle) - (vert[1]-anchor_y)*Math.sin(angle)
        let newY = anchor_y   (vert[0]-anchor_x)*Math.sin(angle)   (vert[1]-anchor_y)*Math.cos(angle)
        new_vertices.push([newX, newY])
    })

    return new_vertices
}

My problem is that the vertices are meant to be relative to the center, but I still want the ability to rotate based on an anchor outside the object. What I'd like to calculate is the x,y translation and the centered rotation that would be equivalent to this anchored rotation. Any help is appreciated.

CodePudding user response:

Defining a similar rotation function for x_pos and y_pos, it would be possible to obtain the offset. Then, for the vertices, apply rotation w/o translation. (anchor=center)

draw(ctx: CanvasRenderingContext2D): void {

    let pos = this.getRotatedPos(angle, anchor_x, anchor_y)

    let verts = this.getRotatedVertices(angle, 0.0, 0.0)
    console.log(this.rotation)
    this.applyStyle(ctx)
    ctx.beginPath()
    for(let i=0; i<verts.length; i  ) {
        //ctx.lineTo(this.x_pos   verts[i][0], this.y_pos   verts[i][1])
        ctx.lineTo(pos.x   verts[i][0], pos.y   verts[i][1])
    }

    :
}


getRotatedPos(angle: number, anchor_x: number, anchor_y: number): [x: number, y: number] {
    let newX = anchor_x   (this.x_pos-anchor_x)*Math.cos(angle) - (this.y_pos-anchor_y)*Math.sin(angle)
    let newY = anchor_y   (this.x_pos-anchor_x)*Math.sin(angle)   (this.y_pos-anchor_y)*Math.cos(angle)
    return [newX, newY]
}
  • Related