简体   繁体   中英

iOS Web App: Rotate the body with the orientation change

I have an iOS Web App game that I designed pixel-perfectly, so it only works in portrait mode (half the game goes below the screen in landscape mode). I want to make it so that if the user rotates the device, the web app will rotate too, forcing the user to rotate it back to portrait mode. I know that I can detect orientation change using "window.onorientationchange", and I can change the style based on orientation using the orient CSS attribute: body[orient="landscape"] or body[orient="portrait"]. Now I just need to know how to rotate the whole body while maintaining the layout. Any help would be greatly appreciated!

使用CSS将旋转变换应用于身体。

 -webkit-transform:rotate(180deg);

After a bit more research, here is what I came up with. This works in my fullscreen web app (the safari navigation bars are too bulky) on my 5th generation iPod Touch

window.onorientationchange = function() {reorient();}

//finds the center of a 90 degree rotation based on the current and projected coordinates of a point, and if the rotation is clockwise or not
function findCenter(curr, next, clockwise) {
    midLenX = (next[0] - curr[0])/2;
    midLenY = (next[1] - curr[1])/2;
    centerX = curr[0] + midLenX + ((clockwise)? -midLenY : midLenY);
    centerY = curr[1] + midLenY + ((clockwise)? midLenX : -midLenX);
    return [centerX,centerY];
}

function reorient() {
    if (window.orientation %180 == 0) { //portrait mode, reset rotation
        document.body.style.webkitTransform = "";
    } else if (window.orientation == -90) { //clockwise rotation
        var center = findCenter([0,0], [960,0], true);
        document.body.style.webkitTransformOrigin = center[0] + "px " + (center[1]-10) + "px";
        document.body.style.webkitTransform = 'rotate(90deg)';
    } else { //counterclockwise rotation
        var center = findCenter([0,0], [0,640], false);
        document.body.style.webkitTransformOrigin = (center[0]-30) + "px " + (center[1]-20) + "px";
        document.body.style.webkitTransform = 'rotate(-90deg)';
    }
}

note that the modified center coordinates in webkitTransformOrigin, like "(center[0]-30)", are merely rough adjustments to account for the status bar. adjust it accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM