From 7d577cc3437c45a1f200afd888c4e30a19fa3cff Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 26 Feb 2024 14:25:57 -0500 Subject: [PATCH 1/2] fix: respect screen DPI --- raylib.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/raylib.js b/raylib.js index a6a0154..3162407 100644 --- a/raylib.js +++ b/raylib.js @@ -107,8 +107,17 @@ class RaylibJs { } InitWindow(width, height, title_ptr) { - this.ctx.canvas.width = width; - this.ctx.canvas.height = height; + // Adjust viewport size according to screen DPI for HiDPI screens. + // see: https://web.dev/articles/canvas-hidipi + const dpi = window.devicePixelRatio || 1; + + const { canvas } = this.ctx; + canvas.height = height * dpi; + canvas.width = width * dpi; + canvas.style.height = `${height}px`; + canvas.style.width = `${width}px`; + this.ctx.scale(dpi, dpi); + const buffer = this.wasm.instance.exports.memory.buffer; document.title = cstr_by_ptr(buffer, title_ptr); } From f8f60077b796a56997271925d001505fdd1fc910 Mon Sep 17 00:00:00 2001 From: x1unix Date: Mon, 26 Feb 2024 14:45:31 -0500 Subject: [PATCH 2/2] fix: return non-scaled size for GetScreen functions --- raylib.js | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/raylib.js b/raylib.js index 3162407..49f31a0 100644 --- a/raylib.js +++ b/raylib.js @@ -32,6 +32,9 @@ class RaylibJs { #FONT_SCALE_MAGIC = 0.65; #reset() { + this.height = 0; + this.width = 0; + this.dpi = window.devicePixelRatio || 1; this.previous = undefined; this.wasm = undefined; this.ctx = undefined; @@ -109,14 +112,18 @@ class RaylibJs { InitWindow(width, height, title_ptr) { // Adjust viewport size according to screen DPI for HiDPI screens. // see: https://web.dev/articles/canvas-hidipi - const dpi = window.devicePixelRatio || 1; - const { canvas } = this.ctx; - canvas.height = height * dpi; - canvas.width = width * dpi; + canvas.height = height * this.dpi; + canvas.width = width * this.dpi; canvas.style.height = `${height}px`; canvas.style.width = `${width}px`; - this.ctx.scale(dpi, dpi); + this.ctx.scale(this.dpi, this.dpi); + + // Store original size for GetScreenWidth and GetScreenHeight calls. + // Necessary as some platforms allow fractional scaling (e.g 1.3) + // and dividing canvas size by DPR can cause rounding issues. + this.height = height; + this.width = width; const buffer = this.wasm.instance.exports.memory.buffer; document.title = cstr_by_ptr(buffer, title_ptr); @@ -132,11 +139,11 @@ class RaylibJs { } GetScreenWidth() { - return this.ctx.canvas.width; + return this.width; } GetScreenHeight() { - return this.ctx.canvas.height; + return this.height; } GetFrameTime() {