ref: 9bcb06ee305455d24ab22f4c8f3556213da1a1ee
parent: 33b5c484295657678ea22db3d57fd19cda96a45e
author: Ben Harris <bjh21@bjh21.me.uk>
date: Sat Dec 10 13:22:54 EST 2022
js: Add a mode where the puzzle tries to fill the viewport This is activated by putting the puzzle in an element with id "puzzlecanvascontain". In that case, the puzzle's default size is as close to filling that element as is achievable. Unlike in the normal mode, this sets the CSS size of the canvas directly. Because it might take a little while for the page to settle down after loading, and because the size of the viewport might change, this listens for "resize" and "load" events, and only bothers changing anything when the page is fully loaded. Waiting for the document to be complete might be a problem if we had images and so forth that we could plausibly be waiting for, but we don't.
--- a/emcclib.js
+++ b/emcclib.js
@@ -574,6 +574,12 @@
* alone and return false.
*/
js_canvas_get_preferred_size: function(wp, hp) {
+ if (document.readyState == "complete" && containing_div !== null) {
+ var dpr = window.devicePixelRatio || 1;
+ setValue(wp, containing_div.clientWidth * dpr, "i32");
+ setValue(hp, containing_div.clientHeight * dpr, "i32");
+ return true;
+ }
return false;
},
@@ -591,6 +597,12 @@
if (resizable_div !== null)
resizable_div.style.width =
w / (window.devicePixelRatio || 1) + "px";
+ else {
+ onscreen_canvas.style.width =
+ w / (window.devicePixelRatio || 1) + "px";
+ onscreen_canvas.style.height =
+ h / (window.devicePixelRatio || 1) + "px";
+ }
onscreen_canvas.height = h;
offscreen_canvas.height = h;
--- a/emccpre.js
+++ b/emccpre.js
@@ -144,6 +144,10 @@
// for positioning the resize handle.
var resizable_div;
+// Alternatively, an extrinsically sized div that we will size the
+// puzzle to fit.
+var containing_div;
+
// Helper function to find the absolute position of a given DOM
// element on a page, by iterating upwards through the DOM finding
// each element's offset from its parent, and thus calculating the
@@ -657,6 +661,24 @@
mql = window.matchMedia(`(resolution: ${dpr}dppx)`);
mql.addListener(update_pixel_ratio);
rescale_puzzle();
+ }
+
+ /*
+ * If the puzzle is sized to fit the page, try to detect changes
+ * of size of the containing element. Ideally this would use a
+ * ResizeObserver on the containing_div, but I want this to work
+ * on KaiOS 2.5, which doesn't have ResizeObserver. Instead we
+ * watch events that might indicate that the div has changed size.
+ */
+ containing_div = document.getElementById("puzzlecanvascontain");
+ if (containing_div !== null) {
+ var resize_handler = function(event) {
+ rescale_puzzle();
+ }
+ window.addEventListener("resize", resize_handler);
+ // Also catch the point when the document finishes loading,
+ // since sometimes we seem to get the div's size too early.
+ window.addEventListener("load", resize_handler);
}
Module.preRun = function() {