Skip to content

Commit dee7a8f

Browse files
authored
fix: setup DPI for canvas element
1 parent a71e743 commit dee7a8f

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

raylib.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,25 @@ function make_environment(env) {
1111
});
1212
}
1313

14+
/**
15+
* Setup correct DPI of canvas element for HiDPI screens.
16+
*
17+
* @see: https://web.dev/articles/canvas-hidipi
18+
*/
19+
function setupCanvas(canvas) {
20+
const dpr = window.devicePixelRatio || 1;
21+
const { height, width } = canvas.getBoundingClientRect();
22+
canvas.height = height * dpr;
23+
canvas.width = width * dpr;
24+
25+
const ctx = canvas.getContext('2d');
26+
if (!ctx) {
27+
throw new Error("Could not create 2d canvas context")
28+
}
29+
ctx.scale(dpr, dpr);
30+
return ctx;
31+
}
32+
1433
let iota = 0;
1534
const LOG_ALL = iota++; // Display all logs
1635
const LOG_TRACE = iota++; // Trace logging, intended for internal use only
@@ -61,11 +80,11 @@ class RaylibJs {
6180
}
6281

6382
const canvas = document.getElementById(canvasId);
64-
this.ctx = canvas.getContext("2d");
65-
if (this.ctx === null) {
66-
throw new Error("Could not create 2d canvas context");
83+
if (!canvas) {
84+
throw new Error('Canvas element not found')
6785
}
6886

87+
this.ctx = setupCanvas(canvas);
6988
this.wasm = await WebAssembly.instantiateStreaming(fetch(wasmPath), {
7089
env: make_environment(this)
7190
});

0 commit comments

Comments
 (0)