nidel
September 4, 2024, 12:30pm
1
Godot Version
4.3
Question
I’d like to embed an exported html version of my game on a web game platform.
I want to keep the width (portrait 9:16 ratio) when stretching the game which is working quite well.
Problem is that the canvas rendering the game still black and I’d like to display some wallpaper behind from the html.
I’ve tried to activate transparent bg settings but nothing seems to work as I’d like to. I’ve seen the canvas_policy settings from the export but no options seems to suit my case as the canvas should follow the window size until the max height is reached.
Any clues on how can I achieve that?
nidel
September 4, 2024, 1:56pm
2
Found this link https://thatstevensguy.com/2022/10/27/maintain-aspect-ratio-with-godot-html5-export/ which helped with some modifications.
In the export settings
Set canvas resize policy to none
Add to include head
<!-- Center canvas in the window. -->
<style>
#canvas {
margin: auto;
padding: 0;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<!-- Resize canvas to maintain 16:9 aspect ratio. -->
<script>
window.addEventListener( 'resize', () => {
const canvas = document.getElementById( 'canvas' );
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const height = ( windowWidth / 16 ) * 9;
if ( windowWidth < windowHeight ) {
canvas.width = windowWidth;
canvas.height = height;
return;
} else if ( windowWidth > windowHeight && height > windowHeight ) {
canvas.width = ( windowHeight / 9 ) * 16;
canvas.height = windowHeight;
return;
}
canvas.width = windowWidth;
canvas.height = height;
} );
window.addEventListener( 'DOMContentLoaded', () => {
window.dispatchEvent( new Event( 'resize' ) );
} );
</script>
*In my case I switched the calculation height for width.
*And watch for load and resize events for triggering the resize function
<style>
#canvas {
margin: auto;
padding: 0;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<!-- Resize canvas to maintain 16:9 aspect ratio. --><!-- Resize canvas to maintain 16:9 aspect ratio based on height. -->
<script>
var resize = () => {
const canvas = document.getElementById('canvas');
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const width = (windowHeight / 16) * 12;
if (windowHeight < windowWidth) {
canvas.height = windowHeight;
canvas.width = width;
return;
} else if (windowHeight > windowWidth && width > windowWidth) {
canvas.height = (windowWidth / 12) * 16;
canvas.width = windowWidth;
return;
}
canvas.height = windowHeight;
canvas.width = width;
};
window.addEventListener('resize', resize)
window.addEventListener('load', resize)
</script>
Then just set a background-image to the body and voilà!