Elastic canvas to always match the full size of the container or screen

I am facing an issue with my responsive canvas that should resize to fit the screen window within a div. The canvas is intended to be 1100x1100 but needs to scale based on the screen size while maintaining a square aspect ratio.

The problem arises when the canvas expands below the screen rather than filling the div size, possibly due to the presence of a top menu navbar and its dynamic behavior. In some cases, the navmenu can collapse or be hidden, making it challenging to adjust the canvas position based on pixels.

How can I resolve this issue to make sure the canvas fits the screen without any scrolling required? Should I look for a CSS solution or turn to Javascript for assistance?

If you try setting the CSS width/height to 100%, you will notice that the square aspect is lost, and the canvas still extends beyond the height viewport. My goal is for the canvas to always remain a square shape. (Please click Full page to see the demo)

// Code snippets here...
// Additional CSS code snippets...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-md navbar-light mb-1" style="background-color: #f2e9e4">
      <!-- Navbar content -->
    </nav>
    
    <div class="container-fluid">
        <canvas id="myCanvas" style="position: absolute; z-index: 1">Your browser does not support HTML5.
        </canvas>
    </div>

Answer №1

To keep the canvas square, you can utilize event listeners for the resize and ready events. Within these events, you can determine the screen width and height to adjust the canvas dimensions accordingly.

Here is an example:

const adjustCanvasHeight = () => {
    let maxSize = $(window).width();
    const otherSizesThatChangeHeight = $('nav').height() + 16 // 16px from body margin;

    if ($(window).height() - otherSizesThatChangeHeight < maxSize) {
        maxSize = $(window).height() - otherSizesThatChangeHeight;
    }

    $idolCanvas.css({
        'width': maxSize,
        'height': maxSize
    });
}

$(document).ready(adjustCanvasHeight);
$(window).on('resize', adjustCanvasHeight);

This code will set the width and height of the canvas to either the window's width or height (whichever is smaller), ensuring it stays within the confines of your window while maintaining a square shape.

Below is the complete code snippet:

// Initialize the canvas
var canvas=document.getElementById("myCanvas");
canvas.width = 1100;
canvas.height = 1100;
var ctx=canvas.getContext("2d");
ctx.fillStyle = "#4A4E69";
$idolCanvas=$('#myCanvas');

// Initialize the drag functionality
var isDragging = false;
var startX;
var startY;

// Arrays of the idols
var idols=[];
var NUM_IDOLS=0;

// Trigger the idols to load
for(var i=0;i<idols.length;i++){
  idols[i].image.src=idols[i].url;
}

//////////////////////////
//// CHECK THIS
//////////////////////////

const adjustCanvasHeight = () => {
    let maxSize = $(window).width();
    let otherSizesThatChangeHeight = $('nav').height() + 16; // 16px from body margin

    if ($(window).height() - otherSizesThatChangeHeight < maxSize) {
        maxSize = $(window).height() - otherSizesThatChangeHeight;
    }

    $idolCanvas.css({
        'width': maxSize,
        'height': maxSize
    });
}

$(document).ready(adjustCanvasHeight);
$(window).on('resize', adjustCanvasHeight);

...

// Additional functions and styling continue below...

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

Webgrid columns lose their width after a postback event

I'm working on a simple webgrid that has 3 columns: View columns: grid.Columns( grid.Column("Applicant Name", format: (item) => @Html.ActionLink((string)item.Name, "EditApplicant", "Applicant", new { id = item.ApplicantId }, null), style: "AppN ...

I am encountering an issue with my PHP code that is causing an error

Whenever I try to submit my form, I keep encountering this error message. Can anyone offer some assistance with this issue? Error: Parse error: syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/u378761662/ ...

Tips for retrieving text without a class or id using selenium and python

I am attempting to extract a list of variables (date, size, medium, etc.) from the following webpage using python/selenium: Getting the titles was straightforward with: titles = driver.find_elements_by_class_name("sln_lot_show") for title in titles ...

Adjust the contents of a DIV depending on which Toggle button is selected

When a user clicks on either "Twin Bed" or "King Bed", the content inside the "demand-message" should change to either "high demand" or "Only ??? rooms left". The ID will remain the same for both buttons due to existing logic. However, the message display ...

After transitioning to TypeScript, the CRA app is encountering issues loading CSS files compiled by SASS

My React application was originally created using create-react-app and I had been successfully loading scss files with the node-sass package. However, after deciding to switch to TypeScript following the steps outlined in , my css files are no longer being ...

Ways to retrieve the scroll position of content within an iframe

I have a webpage with an iframe that loads another webpage. <iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe> I am looking to retrieve the scroll position of the content inside the iframe using Jav ...

Modifying the HTML content of a span element does not always initialize all of its properties

I've been working on setting up a comments-reply system for my website. I have all the necessary PHP files in place, but I'm facing an issue with updating the vote counts dynamically. In the image provided, you can see that upon voting once, I a ...

Using a JSON file as a database for a project featuring HTML, CSS, and Vanilla JavaScript

Our task was to create a project that exclusively utilized JSON files for data storage. The data structure we were working with resembles the following: [ { "aircraftName": "Boeing 747", "departDate": 1640173020000, ...

"Embrace the power of Bootstrap 3 with a cutting-edge logo,

Looking to design a layout that features a logo on the left and a slogan pane with the navigation bar below it on the right. Check out image #1 for reference. As the screen narrows, the plan is to have the navigation pane move below the logo and slogan. T ...

What is the best way to style my text fields in Django using Bootstrap?

In my form class, I have lines that look like this: class ReportForm(forms.ModelForm): diagnosis = forms.CharField(widget=forms.Textarea(attrs={'cols': 200, 'rows': 3})) class Meta: model = Report Then, when I render the form ...

Unable to alter or eliminate the grey background using material-ui

Struggling with a React application that incorporates material-ui. Despite my efforts, I can't seem to get rid of an unwanted grey background in one section of the app. Attempted solutions: body { background-color: #ffffff !important; } * { b ...

Ensure the menu bar remains at the top of the page without using the position:

Check out this awesome fiddle here! My menu bar looks great at the top, but for some reason it won't stay in place when the user scrolls down. I've tried adding position:fixed to the CSS under the first #cssmenu, but it messes everything up. Her ...

Send the value of an li element using AJAX when clicked back to the original page

I'm currently working on passing the data-value of the < li > element that I clicked on to PHP within the same page. My approach involves using AJAX to send the data to PHP for querying purposes. While it seems like the AJAX request is functioni ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

Multiplication and Division with Unit-ed Values in CSS calc() Function

Can you perform multiplication or division with unit-based values using calc() (such as 100%, 5px, etc)? For instance, I wanted to try something like this: width: calc(100% * (.7 - 120px / 100%)); Expecting it to result in something similar to (if 100% ...

Safari doesn't seem to recognize z-index property

Currently, I am utilizing a responsive template to develop a website. An issue arises in Safari where the footer overlaps the navigation bar at the bottom of the page, despite being positioned above it earlier. It appears that the z-index attribute is not ...

Designing Interactive Interfaces using React Components for Dynamic Forms

Is there a way to implement dynamic forms using React Components? For instance, I have a form displayed in the image below: How do I structure this as a React component? How can I incorporate interactivity into this component? For example, when the "+ A ...

The CSS keyframe for mobile devices initiates from 100% and then proceeds to animate

Having some trouble with CSS animations on mobile devices. The animation works perfectly fine on desktop, but on mobile, it seems to display the final 100% keyframe first before animating from 0%. I've tried adding the initial style directly to the cl ...

The problem of Rails redirect_to not working with anchor and will_paginate gem

In my posts controller, I have implemented a feature where upon updating a post, it redirects to the specific post using an anchor tag. The challenge arises when dealing with pagination through the will_paginate gem. I have set up pagination to display fou ...

Affix Object to Bottom of Stationary Element

I have a header element that I want to remain fixed while scrolling. The scrollable area should be positioned directly after the fixed header, without using position: absolute and removing it from the document flow. To better illustrate the issue, I' ...