Kode / Kha

Ultra-portable, high performance, open source multimedia framework.
http://kha.tech
zlib License
1.48k stars 174 forks source link

Use devicePixelRatio in canvas size #1404

Closed RblSb closed 2 years ago

RblSb commented 2 years ago

Update canvas style property to set size in pixels.

This basically re-reverts change https://github.com/Kode/Kha/pull/1309 by @sh-dave after revert in https://github.com/Kode/Kha/pull/1331 by @AndreiRudenko with some vague reason.

After this change, you will get canvas size in real pixels in html5 on any ppi/resolution. To make full-window canvas, you can call this snippet after System.start:

#if kha_html5
import js.Browser.document;
import js.Browser.window;
import js.html.CanvasElement;
import kha.Macros;
#end
...
final canvas:CanvasElement = cast document.getElementById(Macros.canvasId());
final resize = function() {
    final size = getDocumentSize();
    final w = document.documentElement.clientWidth;
    final h = document.documentElement.clientHeight;
    canvas.width = Std.int(w * window.devicePixelRatio);
    canvas.height = Std.int(h * window.devicePixelRatio);
    // You can also call it before System.start if you uncomment this block:
    // if (canvas.style.width == "") {
    //  canvas.style.width = "100%";
    //  canvas.style.height = "100%";
    // }
}
window.onresize = resize;
resize();

There is also some bug on Safari in some tiny portrait orientations, where you can get bigger canvas than screen with my snippet (will still fit full page, but look blurry). This happens because Kha can create canvas with width bigger than screen. To fix this, change canvas element size in index.html to smaller width (like 100px) with khamake flag, so page will don't get scrollbar before full-window code executes.