Pasha S
Pasha S

Reputation: 79

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);

Upvotes: 0

Views: 997

Answers (1)

N3R4ZZuRR0
N3R4ZZuRR0

Reputation: 2412

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>

Upvotes: 2

Related Questions