Skip to content

Instantly share code, notes, and snippets.

@ENAML
Created August 8, 2018 21:28
Show Gist options
  • Save ENAML/a60332dfb86a2eb1ab1daabefdd282f8 to your computer and use it in GitHub Desktop.
Save ENAML/a60332dfb86a2eb1ab1daabefdd282f8 to your computer and use it in GitHub Desktop.
// run
const ctx = initCtx();
const text = `hello my friends`;
draw({ size: 16, fontFace: `monospace` }, text, 10, 50);
// initialize canvas context
function initCtx(w = 600, h = 400) {
// create canvas & ctx
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
// set size
const scale = window.devicePixelRatio || 1;
canvas.style.width = `${w}px`;
canvas.style.height = `${h}px`;
canvas.width = w * scale;
canvas.height = h * scale
// Normalize coordinate system to use css pixels.
ctx.scale(scale, scale);
return ctx;
}
// draw some _monospace_ characters / text
function draw({ size, fontFace }, text, xStart, yStart) {
ctx.font = `${size}px ${fontFace}`;
let x = xStart;
let y = yStart;
for (let c of text) {
const { width: w } = ctx.measureText(c);
// console.log( w );
ctx.fillText(c, x, y);
x += w;
}
x = xStart;
y = yStart + size;
ctx.fillText(text, x, y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment