简体   繁体   中英

How do I make a Canvas HTML picture bigger without losing resolution?

My canvas size is 300x150. I don't want to set the measurements any bigger than this because I'd like it fit on mobile phones as well. But i'd like it to scale up on bigger phones, ipads and laptops without losing resolution. The resolution on my canvas pictures have generally been bad and when it scales up it typically gets even worse. Not sure how to solve this problem. Thanks. https://jsfiddle.net/uwakcgv0/

Here's the HTML:

<canvas width="300" height="150" id="myCanvas"></canvas>

Here's the Javascript:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 300, 150);
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 130);
ctx.lineTo(130, 130);
ctx.stroke();
ctx.fillText("y",18,15);
ctx.fillText("x",135,132);

Increase the canvas size by any factor and then scale the canvas by the same factor (using ctx.scale() ) to get the desired result.

 const SCALING_FACTOR = 2; var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.canvas.width = SCALING_FACTOR * canvas.width; ctx.canvas.height = SCALING_FACTOR * canvas.height; ctx.scale(SCALING_FACTOR, SCALING_FACTOR); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(20, 130); ctx.lineTo(130, 130); ctx.stroke(); ctx.fillText("y", 18, 15); ctx.fillText("x", 135, 132);
 <canvas width="300" height="150" id="myCanvas"></canvas>

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