Hello,
How can I limit the screen size of WebGL game? I want it to have the 16:10 portrait ratio like in mobile phones . Now it is stretched in free space mode and I dont know how to limit its size.
P.S I have to say, I’ve been surprised when I simply did build and run the game for webGL and it worked out of the box… like everything worked as it should… yeah my “game”, doesn’t have any graphics or anything but it did worked very well…
Thx Dear Unity Team.
I did this for my current project. The core of it is to add a js event handler that resizes the canvas element.
The below I copied out of my project … ‘game’ is a div wrapping the canvas element. This will keep the aspect ratio at 16:10 and make it fill as much of the screen as possible. I don’t think it’s necessary to resize the canvas and the game div, that’s a holdover from where I was trying to make the canvas 2x pixel dimensions for retina screens (which Unity currently breaks).
<script type="text/javascript">
window.addEventListener("resize", resizeCanvas, false);
function unityLoaded(){
resizeCanvas();
}
function resizeCanvas () {
var gameDiv = document.getElementById("game");
var canvas = document.getElementById("canvas");
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var pointWidth = Math.round(windowWidth);
var pointHeight = Math.round(pointWidth / 1.6);
if(pointHeight > windowHeight){
pointHeight = windowHeight;
pointWidth = pointHeight * 1.6;
}
gameDiv.setAttribute("style","width: "+pointWidth+"px;height:"+pointHeight+"px;");
canvas.height = pointHeight;
canvas.width = pointWidth;
}
</script>
The ‘unityLoaded’ function is called by my unity game code when it starts running. There’s also a little css to make the canvas etc. have no borders :
* {
margin: 0;
padding: 0;
}
div#game {
margin:auto;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
@Aurigan
Thx for your answer.
I didnt really get your answer: inside of what files should I include this script, and how should I call the unityLoaded() function?..
Check out the documentation for making a custom webGL template (Unity - Manual: WebGL templates) … you can add the JS/css to the index.html
To call a JS function from Unity check out the browser communication docs (Unity - Manual: Interaction with browser scripting)
1 Like