diff --git a/cocos/2d/framework/canvas.ts b/cocos/2d/framework/canvas.ts index a4aef03ff73..87e4eb5e422 100644 --- a/cocos/2d/framework/canvas.ts +++ b/cocos/2d/framework/canvas.ts @@ -124,7 +124,7 @@ export class Canvas extends RenderRoot2D { protected _thisOnCameraResized: () => void; // fit canvas node to design resolution - protected _fitDesignResolution: (() => void) | undefined; + protected fitDesignResolution_EDITOR: (() => void) | undefined; private _pos = new Vec3(); private _renderMode = RenderMode.OVERLAY; @@ -134,16 +134,33 @@ export class Canvas extends RenderRoot2D { this._thisOnCameraResized = this._onResizeCamera.bind(this); if (EDITOR) { - this._fitDesignResolution = (): void => { + this.fitDesignResolution_EDITOR = (): void => { // TODO: support paddings of locked widget this.node.getPosition(this._pos); const nodeSize = view.getDesignResolutionSize(); - Vec3.set(_worldPos, nodeSize.width * 0.5, nodeSize.height * 0.5, 0); + const trans = this.node._uiProps.uiTransformComp!; + + let scaleX = this.node.scale.x; + let anchorX = trans.anchorX; + if (scaleX < 0) { + anchorX = 1.0 - anchorX; + scaleX = -scaleX; + } + nodeSize.width = scaleX === 0 ? nodeSize.width : nodeSize.width / scaleX; + + let scaleY = this.node.scale.y; + let anchorY = trans.anchorY; + if (scaleY < 0) { + anchorY = 1.0 - anchorY; + scaleY = -scaleY; + } + nodeSize.height = scaleY === 0 ? nodeSize.height : nodeSize.height / scaleY; + + Vec3.set(_worldPos, nodeSize.width * anchorX, nodeSize.height * anchorY, 0); if (!this._pos.equals(_worldPos)) { this.node.setPosition(_worldPos); } - const trans = this.node._uiProps.uiTransformComp!; if (trans.width !== nodeSize.width) { trans.width = nodeSize.width; } @@ -160,7 +177,7 @@ export class Canvas extends RenderRoot2D { if (widget) { widget.updateAlignment(); } else if (EDITOR) { - this._fitDesignResolution!(); + this.fitDesignResolution_EDITOR!(); } if (!EDITOR) { @@ -173,9 +190,6 @@ export class Canvas extends RenderRoot2D { this._onResizeCamera(); if (EDITOR) { - // Constantly align canvas node in edit mode - cclegacy.director.on(cclegacy.Director.EVENT_AFTER_UPDATE, this._fitDesignResolution!, this); - // In Editor can not edit these attrs. // (Position in Node, contentSize in uiTransform) // (anchor in uiTransform, but it can edit, this is different from cocos creator) @@ -203,11 +217,7 @@ export class Canvas extends RenderRoot2D { public onDestroy (): void { super.onDestroy(); - if (EDITOR) { - cclegacy.director.off(cclegacy.Director.EVENT_AFTER_UPDATE, this._fitDesignResolution!, this); - } else { - this.node.off(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized); - } + this.node.off(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized); } protected _onResizeCamera (): void {