Skip to content

Instantly share code, notes, and snippets.

@JobLeonard
Last active December 1, 2023 15:54
Show Gist options
  • Save JobLeonard/01350fddaeaeb9023e358e5c28df814f to your computer and use it in GitHub Desktop.
Save JobLeonard/01350fddaeaeb9023e358e5c28df814f to your computer and use it in GitHub Desktop.
subpixel font rendering
canvas {
transform-origin: 0px 0px;
width: 100%;
height: 100%;
/* Legal fallback */
image-rendering: optimizeSpeed;
/* Firefox */
image-rendering: -moz-crisp-edges;
/* Opera */
image-rendering: -o-crisp-edges;
/* Safari */
image-rendering: -webkit-optimize-contrast;
/* CSS3 Proposed */
image-rendering: optimize-contrast;
/* CSS4 Proposed */
image-rendering: crisp-edges;
/* CSS4 Proposed */
image-rendering: pixelated;
/* IE8+ */
-ms-interpolation-mode: nearest-neighbor;
}
<!-- Shamelessly stolen from https://codepen.io/timo22345/pen/avvOmp
except actually showing the difference between { alpha: false } and { alpha: true } -->
<div><canvas width="120" height="120" id="c"></canvas></div>
<pre>{alpha: false}</pre>
<hr>
<div><canvas width="120" height="120" id="c2"></canvas></div>
<pre>{alpha: true}</pre>
const draw = (id, alpha) => {
const canvas = document.getElementById(id);
const ctx = canvas.getContext("2d", { alpha });
ctx.fillStyle = "#EEEEEE";
ctx.fillRect(0, 0, 120, 120);
ctx.fillStyle = "black";
ctx.font = "16px sans-serif";
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textRendering
const textRendering = ["optimizeSpeed", "optimizeLegibility", "geometricPrecision"];
for (let k = 0; k < 3; k++) {
ctx.textRendering = textRendering[k];
for (let i = 0; i < 4; i++) {
ctx.fillText("text", 1 + 30.25 * i, 16 + k * 40);
}
for (let j = 0; j < 4; j++) {
for (let i = 0; i < 4; i++) {
ctx.fillText("t", 1 + (i + j*4) * 6.25, 36 + j * 0.25 + k * 40);
}
}
}
};
draw("c", false);
draw("c2", true);
{"name":"subpixel font rendering","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment