How do you make a scaling canvas without stretch

So, I’ve tried to make a canvas that takes up the entire browser window without stretching the drawings, but every time I try to fix it, it stretches in every case, or returns an error.

<canvas id=“canvas”></canvas>
html {
    width: 100%;
    height: 100%;
}

#game {
    position: absolute;
    width: 100%;
    height: 100%;
}
let canvas = document.getElementById(“canvas”);
let ctx = canvas.getContext(“2d”);
// just sets the canvas drawing surface size to 0px X 0px
canvas.width = canvas.style.width;
canvas.height = canvas.style.height;

CSS

html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

#game-canvas {
    width: 100%;
    height: 100%;
}

JS

const canvas = document.getElementById("game-canvas");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

window.addEventListener("resize", () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});
4 Likes

Problem #1 with that: The “Resize” event is not triggered at the beginning
Problem #2: For some reason, when the window DOES resize, it just sets it to 0 x 0.

Link to REPL: https://replit.com/@Bedrockminer/Full-screen-canvas-test?v=1;

Just so you now, I’m using the Safari browser on a mobile device. Does that have anything to do with Problem #2?(problem #1 is easily fixable)

It is possible that the browser might affect it, but when I tested it, the canvas was resized correctly. I checked the values in the console and they weren’t at 0 after resizing.

image

I also updated my previous answer to solve problem 1

When the canvas gets resized, it doesn’t set the dimensions to 0, 0. Instead, the canvas get cleared.

To prevent this, just set the canvas’s width and height to 100vw and 100vh respectively in CSS.

2 Likes

Try using

canvas.width = window.innerWidth

and

canvas.height = window.innerHeight

You generally set the dimensions of the canvas inside a load event listener, this is what I generally do:

function resize() {
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
}

window.addEventListener("resize", resize);

window.addEventListener("load", function() {
	resize();
	// ...
});

What can happen is the canvas’s dimensions are set before the window is loaded meaning that the window has no dimensions at that point.

3 Likes

None of these seemed to work, but it doesn’t really matter now because I’m making my games in Godot now.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.