What is the best way to create a flexible canvas/grid/row/column that can adapt to changes in browser width and height, all while maintaining its aspect ratio

As someone new to the world of JavaScript, CSS, and HTML, I am eager to learn how to create a game site with multiple games. However, I am feeling lost when it comes to determining the right direction to take. My goal is to develop a game board that can adjust its size dynamically based on the browser's height and width while preserving its original aspect ratio. Additionally, the elements within the game board should resize proportionately with their parent container. While I have experimented with Bootstrap 4's col, row, and container classes, I am struggling to achieve the desired outcome using the container class alone. Recently, I came across a technique involving some other element, which seemed promising in achieving this effect. Can anyone provide me with a clearer understanding of how to implement this?

An excellent example showcasing the resizing functionality I aim for can be found on this website: . By clicking "play game" at the top and adjusting the browser's dimensions, you can observe how the layout adapts seamlessly along with all child elements. This is precisely the effect I aspire to replicate in my own project.

Answer №1

Perhaps this solution will better meet your requirements

let scale = {}, isFirstResize = true;

window.onresize = function() {
    // Ensure that the ctx variable is global or visible in the current scope of your code
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
    if (isFirstResize) {
       isFirstResize = false;
       scale.width = ctx.canvas.width;
       scale.height = ctx.canvas.height;
    } else {
       scale.x = window.innerWidth / scale.width, scale.y = window.innerHeight / scale.height;
       ctx.scale(scale.x, scale.y);

       // Redraw your canvas graphics here
    }
}

Please make sure to:

  • Set your canvas position id to fixed
  • Ensure Canvas top and left properties are set to 0
  • Make sure the ctx variable is globally accessible

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

In Internet Explorer 11, border-radius creates a separation between elements

There is an issue with whitespace appearing around elements that have a border-radius larger than 0, but this only occurs in Internet Explorer. If using border-top-left-radius: 20px; and border-top-right-radius: 20px;: https://i.sstatic.net/MAKsx.png *W ...

An abundant array of options spread across numerous dropdown menus

I have been tasked by a client to do something new that I haven't done before, so I am seeking the best approach. The project involves creating a form with three dropdown menus where users can select from thousands of options. For instance: Users mu ...

"Renaming a file to a custom name in React JS: A step-by-step guide for

Is there a way to custom name the downloaded PDF file when opening it in base64 format using window.open()? Currently, the PDF is being downloaded as "download.pdf" and I would like to specify a different name for the file. Thank you in advance. fetc ...

Creating HTML elements dynamically with attributes based on the `as` prop in React using TypeScript

Is there a way to dynamically create HTML elements such as b, a, h4, h3, or any element based on the as={""} prop in my function without using if guards? I have seen a similar question that involves styled components, but I am wondering if it can be done ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

Designing exquisite button navigation

Hey everyone, I'm currently working on creating a circular button navigation for my website. I want to have 4 buttons, each with a different color, and I want them to glow when the user hovers over them. So far, this is what I have in my HTML: HTML: ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

How to Ensure Screen Opens in Landscape Mode with Phaser3

https://i.stack.imgur.com/keCil.pngIn my Phaser3 game, I am trying to achieve the functionality where the game opens horizontally in a webview without requiring the user to rotate their phone. The vertical photo below shows the game in its current state. W ...

Setting Image Widths for Various Screen Sizes in HTML for Android Tablets and Phones

My android app functions on both tablets and phones, loading content from HTML files in the assets folder. Currently, I am facing an issue where I need different image sizes for tablet and phone devices. Below is the code snippet for displaying the image ...

Using nodeJS to showcase content on a web page

I'm relatively new to NodeJS, and I am trying to figure out if there is a way to utilize NodeJS similar to JavaScript. My goal is to retrieve data from a database and display it within a div on my index.html page. When attempting to use querySelector, ...

Creating a Dynamic Bar in Your Shiny Application: A Step-by-Step Guide

Currently, I am developing a unique crowd funding shiny app to monitor donation amounts. Is there a method available that allows for the creation of a reactive bar in Shiny? Alternatively, is it feasible to achieve this using html, css, and javascript? He ...

Ways to retrieve parameters in getStaticPaths function?

I'm currently working on a Next.js app with Contentful as the CMS. The file structure relevant to my question is: pages -[category] -[slug].js My goal is to access the category value when a user visits category/slug. Currently, I have the category ...

Struggling to connect HTML elements with AngularJS and TinyMCE?

My objective is to edit text using tinymce, persist it in a database, and display it within a div by incorporating angularJS for the same styling and formatting. I am utilizing tinymce 3.5.8 with an angularUI directive. I have successfully saved the wysiw ...

Adding the data from an ajax object response to an array

I'm encountering an issue where my Ajax response is not being properly looped through each object and pushed into the array. I've been stuck on this problem for quite some time now. The Ajax response looks like this... {type:'blog_post&apo ...

Issues with OrbitControls in THREE.js are preventing proper functionality

After setting up my JavaScript code to utilize Three.js OrbitControls, I thought I had everything in place: <script>"OrbitControls.js"></script> As well as: var cameraControls; cameraControls = new THREE.OrbitControls(camera, renderer.dom ...

import template from file using django

With 3 pages containing the same menu at the top of each HTML file, managing updates to all links in the menu can become challenging. To simplify this process, one solution is to create a separate file called menu.txt to store the menu content. By using a ...

execute an action in the controller with the help of JavaScript and refresh the view

My scenario involves having multiple selects such as brands and products. I aim to dynamically update the products options based on the brand selected by the user. The select element looks like this: <select asp-for="Product.BrandId" class=&qu ...

Gradually fade with JavaScript

My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...

Dependency of multiple objects in Webgl three.js

I'm struggling with object dependencies and need help. I want to create a setup where one object is dependent on two other objects. Essentially, when I modify the position of one parent object (like changing the y-Position), the dependent object (chil ...