HTML Canvas resizing challenge

My goal is to resize the canvas to fit inside its parent div within a Bootstrap grid, but I'm running into an issue where the canvas keeps expanding to 2000px x 2000px. Despite successfully resizing based on console.log outputs showing the same dimensions, the 'Hello World' div is simply there for testing purposes.

HTML

        <div class="row justify-content-center">
            <div class="col-10">
                <div class="card">
                    <div class="card-body">
                        <div class="row justify-content-center">
                            <div class="col-8 text-center">
                                <div class="bg-gradient-danger w-100">Hello World</div>
                                <br>
                                <div id="canvasBox"
                                     style="padding: 5px; margin-bottom: 5px;border: 4px solid navy;">
                                    <canvas id="canvas" width="1" height="1"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

Javascript

        let canvas = document.getElementById('canvas');
        let parent = document.getElementById('canvasBox');
        let imgUrl = document.getElementById('canvasIMG');
        let ctx = canvas.getContext('2d');

        let wdt = parent.clientWidth - parseInt(parent.style.paddingLeft) - parseInt(parent.style.paddingRight);
        let ht = parent.clientHeight - parseInt(parent.style.paddingTop) - parseInt(parent.style.paddingBottom);

        console.log(wdt, ht)
        canvas.setAttribute('width', wdt + "px");
        canvas.setAttribute('height', ht + "px");
        console.log(canvas.width, canvas.height)
        ctx.drawImage(imgUrl, 0, 0);
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        

As shown in the screenshot below, the canvas continues to overflow despite efforts to resize it properly.

https://i.sstatic.net/i53YI.png

Answer №1

It's possible that the initial width and height values are incorrect. One solution is to refresh on page load and resize events to ensure the canvas fits correctly:

                  let canvas = document.getElementById('canvas');
        let parent = document.getElementById('canvasBox');
        let imgUrl = document.getElementById('canvasIMG');
        let ctx = canvas.getContext('2d');

        function refresh() {
          let wdt = parent.clientWidth - parseInt(parent.style.paddingLeft) - parseInt(parent.style.paddingRight);
        let ht = parent.clientHeight - parseInt(parent.style.paddingTop) - parseInt(parent.style.paddingBottom);

        canvas.setAttribute('width', wdt + "px");
        canvas.setAttribute('height', ht + "px");

          ctx.fillRect(0, 0, canvas.width, canvas.height);
        };

window.addEventListener('load', refresh);
window.addEventListener('resize', refresh);
    <div class="row justify-content-center">
            <div class="col-10">
                <div class="card">
                    <div class="card-body">
                        <div class="row justify-content-center">
                            <div class="col-8 text-center">
                                <div class="bg-gradient-danger w-100">Greetings World</div>
                                <br>
                                <div id="canvasBox"
                                     style="padding: 5px; margin-bottom: 5px;border: 4px solid navy;">
                                    <canvas id="canvas" width="1" height="1"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

Answer №2

To ensure that the canvas fits perfectly inside the blue box, you can apply the following CSS style: style="width: 100%" to the canvas element.

<canvas id="canvas" style="width: 100%;" height="200px"></canvas>

Although this method does not adjust the height according to the user's window size, using clientHeight may lead to distorted aspect ratios if the user's window is different from the one you are testing in.

By implementing this solution, you will achieve the desired outcome:

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

Displaying or hiding table columns in Vue.js Element-UI el-table based on screen width: a step-by-step guide

Here is my code snippet for generating a table: <el-table :data="tableData" empty-text="No data to display :( " v-if="window.width > 855"> <el-table-column v-for="column in tableColumnsMd" :key=&q ...

Obtain the text from an altered stylesheet in Firefox

I am currently programmatically updating stylesheets for a web page using JavaScript. My method involves having a local copy of the page and all associated assets stored on a server. After I finish making changes to the stylesheets, my goal is to save the ...

Using maxDate in Material UI DatePicker Component to set a maximum date limit

I'm having a tough time getting the maxDate property to function properly on the Material UI DatePicker component. It should disable dates after the specified maxDate. In my situation, I needed to set the maxDate to +60 days from the current Date(), ...

Linkyfy.js does not function correctly with each and not statements

Trying to incorporate a linkifying script on a website, which transforms URLs in text into clickable links. Utilizing the following solution: https://github.com/SoapBox/linkifyjs To make it operational (post-download), the following steps are required: & ...

The switchView feature is currently malfunctioning and unable to access the content on the next page

For my application's admin panel design, I've divided my home into containers. The aim is to display details of clicked items in Images.html and Categories.html when a menu item in the 2nd container (also known as side bar) is clicked. However, m ...

Showing arbitrary text on Vue.js template

In my Vue.js application, I have a Loader component that randomly displays one of several messages. Here is how I implemented it: Vue.component('Loader', { data() { const textEntries = [ 'Just a moment', ...

Is it possible to search for a value within an array of objects in MongoDB, where the value may be found in any object within that array?

Here is the schema: {"_id":"_vz1jtdsip", "participants":{ "blue":["finettix"] "red":["EQm"] }, "win":"red"," __v":0} I have multiple documents l ...

Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this: let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxChunkLength = 3; I am looking to divide this array into multiple arrays as follows: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, ...

I encountered a "Bad Request" error when trying to login through my nodejs server, and I'm unsure of the reason behind this issue. As a beginner in nodejs, I'm still learning the ins and

passport.use(new LocalStrategy(async(email,password,done) => {    try{     const user = await User.findOne({email:email})     if(!user){        return done(null,false,{message:"Invalid email"})     }     const isValidPassword =aw ...

Using Scrapy to extract data from Project Euler's website

Currently, I am working on scraping projecteuler.net using Python's scrapy library as a way to practice my skills. While there are existing implementations of similar scrapers online, they seem too complex for my needs. I simply want to save the probl ...

I need help figuring out how to mention an id using a concatenated variable in the jquery appendTo() method

Using jQuery, I am adding HTML code to a div. One part of this code involves referencing a div's ID by concatenating a variable from a loop. $(... + '<div class="recommendations filter" id="recCards-'+ i +'">' + &apo ...

The JSON output is throwing an error because it is unable to access the property '0' since it is

Trying to convert JSON data into an HTML table, I encountered the following error: "Cannot read property '0' of undefined" <?php $idmatchs = "bGdzkiUVu,bCrAvXQpO,b4I6WYnGB,bMgwck80h"; $exploded = explode(",", $idmatchs); $count = count( ...

Navigating through Sails.Js: A Guide to Implementing Pagination

Looking to implement paginated tables in your application using sails.js, mongodb, and waterline-ORM? Wondering if there is a recommended method for pagination in sails.js? ...

Methods for applying multiple styles within a div using the Document Object Model

Is there a way to add multiple style attributes using DOM `setAttribute` in JavaScript? I've tried doing it but it doesn't seem to work. Can someone provide guidance on how to achieve this? var modify = document.getElementById('options&apo ...

Error Encountered in Request Header of WordPress JSON API

Utilizing the WordPress JSON API plugin has allowed me to effectively retrieve posts and other content from my blog. However, an issue arises when attempting to access the data from my Ionic application. The following error occurs: Request header field A ...

I'm having trouble with my Express server routes not being accessed. The browser is displaying an error message saying 'No Data Received ERR_EMPTY_RESPONSE

I've encountered an issue with my express server while setting up an email service. Despite troubleshooting and simplifying the code to a basic 'hello world' example, the problem persists. No routes are functioning properly – requests made ...

Suggestions for resolving the issue of my header being truncated on mobile browsers?

I am facing an issue with my header and need assistance in fixing it. The problem occurs when scrolling down, as it cuts off a part of the header, but returns to normal when scrolling back up. I suspect the hamburger menu might be causing this issue becaus ...

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

What is the reason behind the Chrome icon flickering momentarily while loading certain web pages?

I recently put together a basic html document, here it is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <title>Just a test.</title> </head> <body> <svg ...

What steps should I take to ensure my navigation bar spans across the entire page?

I'm new to this and looking for help. I want my navigation bar to span the entire width of the page without any white spaces on the sides or top. Below is my CSS: nav ul {list-style-type: none; margin: 0; padding: 0; overflow: hidden; backgr ...