Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises the quality. I attempted a different approach:

const canvas = $("#canvas");
const ctx = canvas[0].getContext("2d");

$(window).on("load", () => {
  canvas.width = $(".board").width();
  canvas.height = $(".board").height();
})
.board {
  height: 40rem;
  width: 90rem;
  background-color: white;
  border: 1px solid black;
}

#canvas {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="header-div">
  <h1>Diagram Modeling Tool</h1>
</div>
<hr>
<div class="work-space">
  <div class="toolbar">
    <p>Components</p>
    <hr class="components-line">
    <div class="components">
      <div class="component arrow">
        <img class="arrow-image" src="images/arrow.png">
      </div>
      <div class="component rectangle">
        <img class="rectangle-image" src="images/rectangle.png">
      </div>
    </div>
  </div>
  <div class="board">
    <canvas id="canvas"></canvas>
  </div>
</div>

My goal is for the canvas to perfectly fit inside the div element it's placed in. Unfortunately, what I end up with looks like this:

https://i.sstatic.net/61C8s.png

Is there a way to adjust the size without distorting the canvas and losing its quality?

Answer №1

When utilizing jQuery, it's worth checking out this solution: How to use jQuery to access Canvas context

I included the usage of [0] in canvas[0].width and canvas[0].height within your jQuery code. Additionally, some drawing commands were incorporated to demonstrate that there is no zoom effect taking place.

const canvas = $("#canvas");
const ctx = canvas[0].getContext("2d");

$(window).on("load", () => {
  canvas[0].width = $(".board").width();
  canvas[0].height = $(".board").height();
  ctx.fillRect(50, 50, 50, 50);
  ctx.fillRect(350, 50, 50, 50);
  ctx.fillRect(350, 350, 50, 50);
  ctx.fillRect(50, 350, 50, 50);
})
.board {
  height: 40rem;
  width: 90rem;
  background-color: white;
  border: 1px solid black;
}

#canvas {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="work-space">
  <div class="board">
    <canvas id="canvas"></canvas>
  </div>
</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 updating the appearance of material-ui table pagination

I'm looking to enhance the way table pagination is presented in material-ui. The current default display by material-ui looks like this: https://i.stack.imgur.com/d4k4l.png My goal is to modify it to look more like this: https://i.stack.imgur.com/A ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

What are the dimensions for maximum picture width and height in the Bootstrap 4 grid class col-4? Additionally, can you provide some tips on minimizing image bl

Hey there! I am trying to arrange 3 screenshots in 3 separate columns in one row, resembling steps 1, 2, and 3. I want them all to have the same size. Can you advise on the maximum width and height I should use before they start getting stretched or comp ...

Retrieving data from a MySQL query output

As a newcomer to PHP and MySQL development, I have created an application in Cordova using Visual Studio. The app functions as follows: The user chooses a serial number from a dropdown menu After selecting a serial number, the corresponding data is displ ...

Using Vue-router and Typescript with beforeEnter guard - utilizing validated data techniques

As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter guard that checks my store to verify the existence of the requested photo. ...

Implementing SVG in NextJS 13 with custom app directory: A step-by-step guide

Recently, I decided to explore the app directory and unfortunately ran into some issues. One of the main problems I encountered was with image imports. While PNG images imported without any problem, SVG images seemed to break when importing in /app. For i ...

What symbol represents the share function in Unicode?

I've combed through Google, Stack Overflow, and various HTML character sites multiple times but have been unable to find the specific icon I'm looking for. Can someone please assist me with obtaining the HTML Unicode sequence for an icon that rep ...

Looking for assistance with aligning a form in the center?

After spending the last hour trying to center a form for a name without success, I have decided to seek help here. Although I have searched extensively, I am still struggling at this point. Here is my HTML: <div id="main" class="main"> <tabl ...

Guide on updating and storing changes in a JSON file named 'file.json' using jQuery or JavaScript

I'm working with a JSON file and attempting to make updates using jQuery. However, I'm encountering an issue where I can't seem to save the update once the script has finished running. Is there a way to save the update without relying on se ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

Watir /Cucumber Element not found: dd-field div.dd-arrow-box (CSS Selector)

Chief complaint: The element cannot be located using CSS Selector Custom Css path: html.ng-scope body.ng-scope div.snap-content div.content-container div.ng-scope div.content-box div div.cb-landing-module div.deposit-acct-box div.dropdown div.dd-field ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

The application of border-radius to a solitary side border forms a unique "crescent moon" shape rather than a traditional semi-circle

Is there a way to transform this shape into a regular semicircle, avoiding the appearance of a moon, and change the image into a circle rather than an ellipsis? http://jsfiddle.net/226tq1rb/1/ .image{ width:20%; border-radius:500%; border-rig ...

What steps do I need to take to retrieve my paginated data from FaunaDB in a React frontend application?

I am facing a challenge when trying to access the data object that contains the keys (letter and extra) in my response from the faunadb database to the frontend react. Although I have used the map function in my frontend code, I have not been successful ...

Difficulty with Launching a Modal using Jquery (jquery-3.6.1.min.js) in Conjunction with Bootstrap 5.2.3

I'm having trouble getting a modal to open with jQuery after upgrading to newer versions of JQuery and Bootstrap. Any suggestions? JQUERY CODE - $("#exampleModal").modal(); JSP CODE - I followed the code from the Bootstrap website : ...

Encountered an issue while processing the firebase get request with the following error message: 'Unauthorized request in Angular'

Here are my rules: Utilizing a Firebase database Calling an API URL from this section https://i.stack.imgur.com/auAmd.png I am attempting to retrieve data from a Firebase API in an Angular application, but I keep encountering an 'Unauthorized reque ...

Changing the class when a checkbox is selected using JQuery

I’m working on a bootstrap switcher and I want to change the panel color from grey to green when the checkbox (switch) is checked. I had it working before, but after updating the switcher, it no longer functions properly. Here is the main code for the s ...

Learn the process of dynamically populating an HTML table with data using JavaScript and JSON

I have developed a code snippet to dynamically add an HTML table without using jQuery. The code serves as an application from the server to the client, where the client receives a JSON object to parse into a string. Here is how you can add an HTML table ...

SQL table not being updated by AJAX request data submission

I'm encountering an issue when trying to update a SQL table with form data sent via a JQuery AJAX POST. Even after using mysql_error(), no errors are being returned. As a troubleshooting step, I appended "-Test Test" to my textarea input. This addi ...

Unable to transfer card from the top position in the screen

Utilizing Tailwind (flowbite) for the frontend of my project, I encountered an issue where the Navbar was overlapping the Card. I attempted using mt-8 to resolve the problem, but it did not yield significant changes. What adjustments should I make to achi ...