aboutsummaryrefslogtreecommitdiff
path: root/emccpre.js
diff options
context:
space:
mode:
authorBen Harris <bjh21@bjh21.me.uk>2022-12-05 14:02:59 +0000
committerBen Harris <bjh21@bjh21.me.uk>2022-12-10 15:30:49 +0000
commit02f1d55a023eeab52b20cb5db6428f8ff40b9459 (patch)
treef0030f9a6ed37827c8b0d0a8835eed3d8e62ecf9 /emccpre.js
parenta3310ab857f088489b35ebf10733ba284a24d27f (diff)
downloadpuzzles-02f1d55a023eeab52b20cb5db6428f8ff40b9459.zip
puzzles-02f1d55a023eeab52b20cb5db6428f8ff40b9459.tar.gz
puzzles-02f1d55a023eeab52b20cb5db6428f8ff40b9459.tar.bz2
puzzles-02f1d55a023eeab52b20cb5db6428f8ff40b9459.tar.xz
js: Allow CSS to set the font used by the puzzle
This means that the calculated font properties of the HTML canvas now control what font is used. The size is overridden, and for monospaced text so is the family. I'd like to be able to also specify the monospaced font, maybe using a CSS variable, but that looks like being quite a lot of extra complexity. My experience when testing this was that constructing a valid "font" string for a canvas context is prone to breakage, but broke in a way that left the font unchanged, so we always set a simple specification first before trying to construct one from CSS.
Diffstat (limited to 'emccpre.js')
-rw-r--r--emccpre.js16
1 files changed, 16 insertions, 0 deletions
diff --git a/emccpre.js b/emccpre.js
index 4cd5787..f7e0cc5 100644
--- a/emccpre.js
+++ b/emccpre.js
@@ -179,6 +179,22 @@ function canvas_mouse_coords(event, element) {
return {x: rcoords.x * xscale, y: rcoords.y * yscale}
}
+// Set the font on a CanvasRenderingContext2d based on the CSS font
+// for the canvas, the requested size, and whether we want something
+// monospaced.
+function canvas_set_font(ctx, size, monospaced) {
+ var s = window.getComputedStyle(onscreen_canvas);
+ // First set something that we're certain will work. Constructing
+ // the font string from the computed style is a bit fragile, so
+ // this acts as a fallback.
+ ctx.font = `${size}px ` + (monospaced ? "monospace" : "sans-serif");
+ // In CSS Fonts Module Level 4, "font-stretch" gets serialised as
+ // a percentage, which can't be used in
+ // CanvasRenderingContext2d.font, so we omit it.
+ ctx.font = `${s.fontStyle} ${s.fontWeight} ${size}px ` +
+ (monospaced ? "monospace" : s.fontFamily);
+}
+
// Enable and disable items in the CSS menus.
function disable_menu_item(item, disabledFlag) {
item.disabled = disabledFlag;