旋转由多个其他旋转对象组成的对象

时间:2016-10-26 23:25:54

标签: javascript canvas typescript rotation

我想将一个对象渲染到我根据其方向旋转的画布。但是,此对象由多个其他对象组成,这些对象也应该能够独立旋转。

据我所知,保存和恢复上下文是有问题的部分,但我该如何实现呢?

class MotherObject {
    childObject1: ChildObject;
    childObject2: ChildObject;
    constructor(private x: number, private y: number, private direction: number, private ctx: CanvasRenderingContext2D) {
        this.childObject1 = new ChildObject(this.x + 50, this.y, 45, this.ctx);
        this.childObject2 = new ChildObject(this.x - 50, this.y, 135, this.ctx);
    }
    render(): void {
        this.ctx.save();
        this.ctx.translate(this.x, this.y);
        this.ctx.rotate(this.direction * Math.PI / 180);
        this.childObject1.render();
        this.childObject2.render();
        this.ctx.restore();
    }
}
class ChildObject {
    constructor(private x: number, private y: number, private direction: number, private ctx: CanvasRenderingContext2D) { }
    render(): void {
        this.ctx.save();
        this.ctx.translate(this.x, this.y);
        this.ctx.rotate(this.direction * Math.PI / 180);
        this.ctx.fillRect(0, 0, 100, 20);
        this.ctx.restore();
    }
}

1 个答案:

答案 0 :(得分:0)

完整的图像渲染功能。

2D API允许您绘制缩放,旋转,淡入/淡出的图像。渲染这样的图像有时被称为精灵(从旧的16位日起)

用于围绕其中心旋转绘制缩放的旋转褪色图像/精灵的功能。 xy是画布中心所在的位置。 scale为1表示无刻度,< 1表示较小,> 1表示较大。 rot是旋转,0表示无旋转。 Math.PI是180度。增加的腐烂将以顺时针方向旋转,减少将以另一种方式旋转。 alpha将设置图像的透明度,0表示不可见,1表示完全可见。尝试使用0-1范围之外的值设置全局alpha将不会导致任何更改。下面的代码进行检查以确保alpha被钳制。如果您信任Alpha值,则可以直接设置globalAlpha

您可以调用此函数而无需恢复状态,因为setTransform会替换现有转换,而不是像ctx.translatectx.scalectx.rotate,{{1}那样将其相乘}

ctx.transform

该函数保留当前变换和alpha。如果在其他地方渲染(不使用此函数),则需要重置2D上下文的当前状态。

默认

function drawSprite(image,x,y,scale,rot,alpha){
     // if you want non uniform scaling just replace the scale 
     // argument with scaleX, scaleY and use 
     // ctx.setTransform(scaleX,0,0,scaleY,x,y);
     ctx.setTransform(scale,0,0,scale,x,y);
     ctx.rotate(rot);
     ctx.globalAlpha = alpha < 0 ? 0 : alpha > 1 ? 1 : alpha; // if you may have 
                                                              // alpha values outside
                                                              // the normal range
     ctx.drawImage(image,-image.width / 2, -image.height / 2);
}
// usage
drawSprite(image,x,y,1,0,1); // draws image without rotation or scale
drawSprite(image,x,y,0.5,Math.PI/2,0.5); // draws image rotated 90 deg
                                         // scaled to half its size
                                         // and semi transparent

保持当前状态

ctx.setTransform(1,0,0,1,0,0);
ctx.globalAlpha = 1;