Tips for automatically adjusting canvas size within a parent container

I am facing a challenge with a canvas element inside a div:

<div class="preview"><canvas id="cropped" width="2480" height="2003"></canvas></div>

The div block is smaller than the canvas. How can I make the canvas autofit in two different scenarios:

  1. Automatically adjust canvas width proportionally to parent div's width
  2. Automatically adjust canvas height proportionally to parent div's height

I have attempted the following approach:

public autofit = (orientation: RegistryOrientation) => {
    let previews = document.getElementsByClassName('preview');

    if (previews.length > 0) {
        let preview = previews[0];
        let width = preview.clientWidth;
        let height = preview.clientHeight;

        if (orientation === RegistryOrientation.album) {
            this.imgCanvas.style.width = width + 'px';
            this.imgCanvas.style.height = 'auto';
        } else if (orientation === RegistryOrientation.book) {
            this.imgCanvas.style.height = height + 'px';
            this.imgCanvas.style.width = 'auto';
        }
    }
};

Answer №1

To indicate proportional height based on the parent element, you can utilize the '%' symbol. Check out this example in your CSS:

#cropped {
  width: 100%;
  height: 80%;
}

Answer №2

Here is the solution you were looking for:

div {
  border: 1px solid red;
  width: 200px;
  height: 200px;
  resize: both;
  overflow: hidden;
}

canvas {
  border: 1px solid blue;
  aspect-ratio: 1 / 1;
  box-sizing: border-box;
  max-width: 100%;
  max-height: 100%;
  margin: auto;
}
<div><canvas width="1000" height="1000"></canvas></div>

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

Tips for linking weight scale device to a website

I recently developed a web application that calculates the weight of products. The application was created using PHP, JavaScript, and AJAX, running on a XAMPP server. Now my client is requesting for me to integrate a weight scale machine into the applica ...

Tips for transferring a JavaScript variable to a Java servlet using the doPost method

I am working with an HTML table that contains dropdowns. When a user clicks on a dropdown, I store the column name and corresponding row (billdate) in a variable. Now, my goal is to pass this variable to my Java servlet's doPost method and then use it ...

What is preventing me from extracting all information from online shopping sites?

Recently, I've been tackling a project that involves scraping data from various e-commerce websites. However, I've encountered difficulties in extracting the desired information from these sites. For instance, when attempting to scrape all the li ...

Creating dynamic images with PHP GD library

I am encountering a problem where Hindi text added to an image using PHP GD is appearing as squares. It seems like PHP GD does not support rendering Hindi text properly. Is there a solution to fix this issue? Alternatively, are there any other methods to ...

The use of the jQuery clone() method in conjunction with jQuery TABS allows for the display of cloned fields

I've implemented jQuery tabs with the following code structure: <ul class="tabNavigation" id="tabs"> <li><a href="#AAA">AA</a></li> <li><a href="#BBB">BBB</a></li> </ul> ...

What could be the reason why csg.js in Three.js is not functioning correctly?

I attempted to utilize csg.js functions for cutting a sphere out of a box, but unfortunately it doesn't seem to be working correctly. I have gone through the tutorial on without success. <html> <head> <title>Experiment& ...

Using jQuery to add or remove multiple classes at once

My navigation tabs use jQuery to add and remove classes for the active tab. However, I'm facing an issue where the active class is not removed when a new tab is clicked or when the user scrolls to a new section. Please refer to the following gist for ...

Encountering issues while trying to incorporate a trading chart library into an Angular 7 project

ERROR in src/assets/datafeeds/udf/src/udf-compatible-datafeed-base.ts(243,74): error TS2339: 'errmsg' Property Not Found The property 'errmsg' does not exist on the type 'UdfErrorResponse | UdfSearchSymbolsResponse'. The p ...

I am looking for a pair of HTML tags that will allow one to be visible while the other is hidden, and then switch when needed

I am in the process of constructing a webpage dedicated to learning Japanese vocabulary. Each word will be presented within a sentence, just like the example shown below. 森林に散歩する take a walk in the forest In order to facilitate the practic ...

What is the proper way to incorporate a randomly generated number from a variable into a JSON index retrieval?

For my project, I am working on a slideshow that pulls image URLs from a JSON file containing 100 images. However, I only want to display 5 random images from the JSON each time the page loads. The HTML is styled within a style tag in an EJS file that is l ...

Sending input data without a form

Currently, I am in the process of developing a website game and facing a challenge with implementing a feature I refer to as "dialogue". Initially, I attempted to address this issue by using a form element, but encountered a problem where pressing enter o ...

Using React's Context API to access context within a function and addressing the issue of undefined errors

I'm currently working on a project where I need to create a global variable that toggles between false and true as the user navigates between different views. My approach involves utilizing the Context API to establish this global variable. I have cre ...

Controlling Formatting in ASP.NET

Feeling puzzled by a seemingly simple question with no clear solution in sight. We're attempting to transition an interface to an ASP.NET control that currently appears like this: <link rel=""stylesheet"" type=""text/css"" href=""/Layout/CaptchaLa ...

Troubles with CSS in MUI Component Integration

How can I successfully implement a vertical timeline using Material UI in React? I've set it up, but the CSS isn't functioning as expected. Is there an error in my implementation? List of Dependencies: "@emotion/react": "^11.11.1& ...

Is it possible to use a '.JS' file downloaded through Node Package Manager (npm) directly in a web browser?

Generally, I am looking to utilize a specific library without relying on Node CMD. For instance: I aim to create a TypeScript playground without having to execute 'tsc.cmd' from "npm\node_modules", instead, I want to directly call the tsc c ...

Triggering click events using requireJS and jQuery

I am currently utilizing requireJS in my project. Within my codebase, I have two essential files, one containing the main app configuration and functions: app/main.js define(["jquery", "jquery_migrate"], function() { return { bar: function() ...

Issue with CSS: Dropdown menu is hidden behind carousel while hovering

I'm struggling with adjusting the position of my dropdown list. It keeps hiding behind the carousel (slider). When I set the position of the carousel section to absolute, it causes the navbar to become transparent and the images from the carousel show ...

Issue: Compilation unsuccessful due to an error in the Babel loader module (./node_modules/babel-loader/lib/index.js). Syntax error

I'm currently exploring how to integrate the Google Maps Javascript API into my VueJs project without relying on the vue2-google-maps package (as it seems too restrictive to me). Here's what I've done so far, after registering my Vue compon ...

Fill the table according to the selected criteria

One issue I am facing is that the table does not get cleared when using the arrow keys to navigate through select options. As a result, the data from the JSON is populated in sequence and does not match the currently selected option. Does anyone have any ...

JavaScript code to locate the most pertinent strings within an array based on a specific substring

I'm working with a large array containing names of people, such as: let names = [ "John Brown", "Tristan Black", "Carl Jobbs", "Aidan Burrows", "Taylor Joe" ]; When given an input, I want to return the top 5 most relevant results ...