+ 2
Resize Canvas
I'm trying to make a project using canvas, but I can't seem to resize the canvas using %. If I do it in HTML the canvas resizes with pixels. In CSS the quality of the canvas is lowered. In JavaScript it just breaks the canvas. How can I resize the canvas depending on the users screen without lowering the canvas quality? https://code.sololearn.com/WAYQeutAfeXe/?ref=app
2 Answers
+ 6
Run this to watch how CSS and HTML canvas scaling properties interact:
https://code.sololearn.com/WETCkRaPNVhy/?ref=app
I'm using pixels. To calc by "viewport" using "vh" and "vw" for percentage of viewport height and width:
Line 28... let's use 50, to test scaling up to 50% of the user's view:
var maxOuterDimension = 50; // was 200 for use as pixels
Lines 67-68, change the units from "px" to viewport-relative height / width:
theCanvas.style["height"] = cvsContainerHeight + "vh"; // was 'px'
theCanvas.style["width"] = cvsContainerWidth + "vw"; // was 'px'
And run. The units are required when setting styles this way (the engine does weird things if you omit them).
0
You have to redefine canvas rendering according to the window size:
```javascript
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
function fitCanvas() {
const originalWidth = canvas.width;
const originalHeight = canvas.height;
// Calculates pixelratio
const windowRatio = window.innerWidth / window.innerHeight;
const canvasRatio = originalWidth / originalHeight;
// Initialize the variables
let newWidth, newHeight;
//Defines the new width and height based on the window
if (windowRatio > canvasRatio) {
newWidth = window.innerHeight * canvasRatio;
newHeight = window.innerHeight;
} else {
newWidth = window.innerWidth;
newHeight = window.innerWidth / canvasRatio;
}
// Adjusts Canvas Resolution (the internal pixels)
canvas.width = originalWidth; // Maintains the original width for the internal proportion
canvas.height = originalHeight; // Maintains the original height for the internal proportion
// Adjusts Canvas Style (Canvas CSS)
canvas.style.width = `${newWidth}px`;
canvas.style.height = `${newHeight}px`;
}
fitCanvas(); // Call the function initially
window.addEventListener('resize', fitCanvas); // Call the function whenever the window is resized
```
Use this along with the `ctx.scale ()` scale to climb the objects drawn in canvas using pixelralio.