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:

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

Using a callback function with jQuery in a focus event

Is there a way to ensure that a callback function inside a focus() is only played once while the element has focus? For example, in the code snippet below, the alert('ok') will continue to be triggered as long as the textarea maintains focus. Is ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

Discovering ways to showcase JSON response in JavaScript or PHP

Currently, I am integrating the Coin Warz API into my website. The API sends responses in JSON format. I have attempted to display this data in a table format using PHP, but unfortunately, I am encountering difficulties. The JSON Response is as follows: [ ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

Tips for creating horizontal scrolling in the div element

I'm working with a div element that looks like this: <div id="tl" style="float:right;width: 400px; height:100px; background-color:Green; overflow-x: scroll;overflow-y: hidden;"> <div id='demo' style="float:left;height ...

A guide on arranging the JSON array within an AngularJS controller

Can someone assist me with sorting the JSON list provided below in the controller and then displaying it in the view? The orderBy filter only sorts one level, but I need it to sort recursively for all children. Input: R2 -->S4 ------>T5 ------> ...

How to showcase images and text from an array of objects using React

I'm currently working on a React lightbox that is supposed to display a loop of objects containing images and text. However, I'm facing an issue where the images are not showing up with the corresponding text label as intended. It seems like I a ...

Need inspiration for testing web content with Protractor?

Exploring new possibilities for testing web content with Protractor. Any fresh ideas on what else can be tested? So far, I've checked links to ensure they redirect correctly. I've also verified text color and decoration changes when hovering ove ...

"Converting domain names with punycode and utilizing Firebase for a

My current project involves updating a Firebase app with NextJS, and I've encountered an issue that needs to be resolved. Upon running the command: % npm run build I received the following message: (node:3719) [DEP0040] DeprecationWarning: The `pun ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

reloading a URL dynamically using an array in JavaScript

I need assistance with a Chrome extension code. The goal is to have it check the page that initially loads, and if it matches my website st.mywebsite.com, execute the specified code. Currently, it does not perform this check and runs on every loaded page ...

Is it possible to create a resizable menu without distorting its appearance?

After setting up a menu on my website, I noticed that when resizing the window, it spills over into other divs on the same line. Despite trying multiple solutions, I have been unsuccessful in resolving this issue. The navigation for the menu is contained w ...

The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code: <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script> <script type="text/javascript"> var textWrapper = document.querySelector('.ml6 .letters'); textWrapper.in ...

Automatically populate a dropdown menu with options based on the user's birth date

I successfully managed to populate the drop-down fields for months, days, and years. Furthermore, I was able to calculate the age of the user; however, I have restricted it to a maximum of 13 years. Check out the code snippet below: $('#reg-yr' ...

Utilizing jQuery to attach events to dynamically generated elements

I have a scenario where I am uploading multiple images and inserting them into specific div elements. These divs should toggle a class when clicked. Should I include the part of code that adds the onclick event inside the ajax success function? Your help i ...

Chrome Automatically Playing WebRTC Audio

My webapp has webrtc functionality, but I've noticed a strange issue. When connections are established between Chrome browsers, the audio is not played, while video is. However, this problem doesn't occur with Mozilla users. So... Chrome user 1 ...

What is the best way to allow all authenticated routes to display the Devise ajax Login form?

I have successfully incorporated Devise to accept Ajax Login and have designed a form for logging in via ajax, displayed within a modal. However, I am only able to view the form and login when I set up event binders for specific buttons that activate the m ...

What is the process of retrieving data from a Nextjs API route during the build and deployment stages?

I'm currently facing an issue while trying to deploy my nextjs web app on vercel. Upon deployment, I encounter the following error: > Build error occurred FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUS ...

Fixed Positioning Div to Stay at the Top while Scrolling

Currently, I have successfully implemented the functionality to stick the div to the top once it scrolls down by 320px. However, I am curious if there is an alternative approach to achieving this effect. Below is the code snippet I am using: jQuery(functi ...