What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it.

SOLVED

var RATIO = 480 / 800; // Initial ratio.
function resize() {
    var DEVICE_WIDTH = window.innerWidth,
        DEVICE_HEIGHT = window.innerHeight,
        ratio = DEVICE_WIDTH / DEVICE_HEIGHT,
        scale = 1;
    // Adjusting scale based on window size changes
    if (ratio > RATIO) { 
        scale = DEVICE_HEIGHT / 800; // Divide by original viewport height
    } else { 
        scale = DEVICE_WIDTH / 480; // Divide by original viewport width
    }
}

// Now you just need to apply this scale factor in your draw method for every element (x and y coordinates, width and height)

I hope this solution helps someone who was in the same boat as me :)

Answer №1

Suppose you have assigned the name canvas to your canvas element. The following code snippet can be used to resize the canvas without distorting its proportions:

function adjustSize(w, h)
{
    canvas.width = w; 
    canvas.style.width = w + "px";
    canvas.height = h; 
    canvas.style.height = h + "px";
}

//To implement this,
adjustSize(400, 250);

Answer №2

To customize it dynamically, adjust the settings as needed. For example, if your container has a specific ID or class

var container = document.getElementById(containerId);

var setDimensions = function(element) {
    return function (width, height) {
          element.style.width = width;
          element.style.height = height;
     }
}

var resizeListener = setDimensions(container)(document.documentElement.clientWidth,document.documentElement.clientHeight);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to run a Bash script using PHP

I'm currently facing a challenge while attempting to run a simple Bash Script from within a PHP script. The process involves collecting data from an interactive HTML5 front-end page, transmitting it through ajax to the PHP script, parsing the variable ...

What causes materialui styles to vanish upon refreshing in nextjs?

After consulting the materialui documentation (https://material-ui.com/guides/server-rendering/), I was able to find a solution, but I am still unsure of the underlying reason. Why does the style work initially during rendering but disappear upon subs ...

"How to retrieve data from a nested object in MongoDB by referencing variables

I am facing an issue with accessing nested objects using a variable in the npm package mongojs. Despite my efforts, the code snippet below is not working as expected: let userID = req.user._id, marketName = req.body.marketName, itemNam ...

Tips for positioning two fields side by side on a webpage with CSS

I currently have two datepickers aligned vertically and I'm looking to display them in a horizontal layout with some spacing between them. What changes do I need to make in order to present these two calendar pickers side by side on the same row? Cou ...

Is nesting ajax calls in jQuery a clever strategy?

I currently have this ajax call: $.ajax({ url: "misc/sendPM.php", type: "POST", data: data, success: function(stuff) { if (typeof stuff == "object") { var err = confirm(stuff.error); if (err) { ...

Javascript error - SyntaxError: unexpected token '}' after property list is missing

In my code snippet below: var UserCharacter = { UserID: util.getCookie('u_u'); userUsingThisCharacter: function() { var data = {}; data.UserID = UserCharacter.UserID; $.ajax({ type: "GET", url: util.API_URL + "charact ...

splitting up the lengthy list into manageable chunks according to the screen dimensions

How can I make the blue color row-based list (the divs inside a div with id phrase) break on the next line based on the screen size? Any suggestions on additional changes needed in the following CSS? #phrase { color: #fff; position: ...

Unintended redirects are occurring with AJAX requests when using the send() method

After loading the web page, I utilize AJAX to populate a list asynchronously. However, when the AJAX request is sent to retrieve data for the list box, instead of receiving JSON data as expected, an unintended web page containing the list box is returned. ...

Store the information from an AJAX post request in a div element into the browser

I've set up a datatable with a button that posts data into a div. Below is the HTML code I used: HTML : <div class="card-body"> <div class="overlay" id="kt_datatable_nodata"> <div class="o ...

Refreshing data attribute following an ajax request

I have this page with a list of various job listings. Each job listing has a button labeled "Paid" that includes a data-paid attribute indicating whether the job is paid or not. Whenever the "Paid" button is clicked, it sends a request to my route which u ...

Is it possible to leverage Create-React-App's npm start in conjunction with Node.js?

I've recently started diving into React and node.js. My goal is to have a node.js server that can serve up React.js pages/views. After running 'create-react-app' and then using 'npm start', I'm not sure if I also need to man ...

What are some effective strategies for avoiding empty fields showing on an email form?

My HTML form is linked to a PHP Email handler, and it's working well except for one issue. When the email is delivered, it includes all fields, even the empty ones. I want it to only display filled-in fields. I tried using an IF statement that checks ...

Ever since implementing a new section class, the CSS first-of-type selector has ceased to function

After referencing a previous response, I utilized first-of-type to specifically target the initial menuSection with this code snippet... .menuSection:first-of-type { background: red; } <div id="container"> <section class="menuSection"> ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. ...

Implement a fadeout effect by using a timeout function that adds a class to the div element in

I implemented a loader on my webpage that animates for 3 seconds before a function kicks in to modify the styles and make it invisible. I am looking to add a fadeout effect when the 'waa' style is applied to the 'load' div. setTimeou ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...