Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I scale the HTML5 canvas without making it blurry?

I have created a canvas using the following markup:

<canvas id="canvas"></canvas>

Now, if I specify width and height here directly, then the drawings on canvas will be pretty sharp.

<canvas id="canvas" width="600px" height="400px"></canvas>

but this way I can't scale the canvas flexibly to cover every screen size. Using vh or vw instead of pixels doesn't work either. I tried setting them in JavaScript like:

$('#canvas').css({
   "height": window.innerHeight,
   "width": window.innerWidth
 });

this covered the whole canvas but made the lines blurry. Is there some way I can get sharp images while the canvas still covers whole screen?

I tried using:

$("#canvas")
.prop("width", window.innerWidth)
.prop("height", window.innerHeight);

but the objects on the canvas (for example a circle that I drew) are still blurry. When I open up devTools, I see the following markup:

<canvas id="canvas" style="height: 768px; width: 1366px;"></canvas>

So, I guess width and height are still being defined by CSS.

like image 737
Neena Vivek Avatar asked Jan 05 '23 10:01

Neena Vivek


2 Answers

Canvas CSS properties do not resize canvas, they rescale it.
You may simply change the properties with your JS:

$("#canvas")
    .prop("width", window.innerWidth)
    .prop("height", window.innerHeight); 
like image 73
Yeldar Kurmangaliyev Avatar answered Jan 13 '23 10:01

Yeldar Kurmangaliyev


try:

var canvas = document.getElementById('canvas');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
like image 26
lsv Avatar answered Jan 13 '23 09:01

lsv