简体   繁体   中英

How can I resize the canvas element in html without zooming it and losing quality?

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:

图片

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM