I have been busy recently. I haven't seen ch5 for a long time. Now ch5 has been officially released, and api and template files have changed significantly. I believe that it is okay if there are basic people to adapt to new changes, so I am not planning to rewrite the previous blog about ch5.
After reading the helloworld example of the new version, we found that the game interface was scaled by an adaptive browser window. After carefully reading this example, I found some shortcomings.
1. the zoom adjustment function is written in a scene file.
2. the zoom effect is not very good. When the aspect ratio of the window and the target aspect ratio are different, a scroll bar appears.
3. No vertical and horizontal center
So I modified it:
1. Extract the scaled function to a single unit.
[Javascript]
// Global functions of GameFunc. js games
Var Game = Game || {};
Game. Func = (function (){
Var instance;
Function constructor (){
Return {
AdjustSizeForWindow: function (){
// Target Aspect Ratio
Var targetRatio = cc. originalCanvasSize. height/cc. originalCanvasSize. width;
// Window Aspect Ratio
Var winRatio = window. innerHeight/window. innerWidth;
// Reset the canvas size to make the canvas aspect ratio the same as the target aspect ratio.
// Set the height or width to be the same as the window size based on the ratio.
If (winRatio <= targetRatio ){
Cc. canvas. height = window. innerHeight;
Cc. canvas. width = window. innerHeight/targetRatio;
} Else {
Cc. canvas. height = window. innerWidth * targetRatio;
Cc. canvas. width = window. innerWidth;
}
// Zoom Ratio
Var xScale = cc. canvas. width/cc. originalCanvasSize. width;
// Set vertical and horizontal center
Var parentDiv = document. getElementById ("Cocos2dGameContainer ");
If (parentDiv ){
ParentDiv. style. width = cc. canvas. width + "px ";
ParentDiv. style. height = cc. canvas. height + "px ";
ParentDiv. style. position = "absolute ";
ParentDiv. style. top = "50% ";
ParentDiv. style. left = "50% ";
ParentDiv. style. marginLeft = (-cc. canvas. width/2) + "px ";
ParentDiv. style. marginTop = (-cc. canvas. height/2) + "px ";
}
// Reset coordinates
Cc. renderContext. translate (0, cc. canvas. height );
// Content Scaling
Cc. renderContext. scale (xScale, xScale );
Cc. Director. getInstance (). setContentScaleFactor (xScale );
}
}
}
Return {
GetInstance: function (){
If (! Instance ){
Instance = constructor ();
};
Return instance;
}
}
})();
This is a single unit of delayed instantiation, because some ch5 classes cannot be used before the game is loaded.
2. modify main. js, adjust the scaling after the game is loaded, and monitor the resize of the window.
In the applicationDidFinishLaunching function, add the following code before return
[Javascript]
Game. Func. getInstance (). adjustSizeForWindow ();
Window. addEventListener ("resize", function (event ){
Game. Func. getInstance (). adjustSizeForWindow ();
});
OK...