0

I am developing a basic modeling app on web. I have a board as a canvas element. I am trying to set its size. When I set its height and width in css, it scales the entire canvas and that loses quality. I tried to do it like this instead:

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>

I want it to completely cover the size of the div element it is in. Instead, what I get is this:

image

How can I set the size without scaling the canvas and losing quality?

Bumhan Yu
  • 2,078
  • 1
  • 10
  • 20
darkman106
  • 27
  • 1

1 Answers1

0

As you are using jQuery, you might want to read the following answer: jQuery equivalent of getting the context of a Canvas

I added [0] to canvas[0].width and canvas[0].height to your jQuery code and then added some drawing calls to show that nothing is being zoomed.

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>
PeterJames
  • 1,137
  • 1
  • 9
  • 17