Skip to content

Instantly share code, notes, and snippets.

@alexmccabe
Created March 22, 2018 15:22
Show Gist options
  • Save alexmccabe/3038310b474b119dc369ce5215cb4a54 to your computer and use it in GitHub Desktop.
Save alexmccabe/3038310b474b119dc369ce5215cb4a54 to your computer and use it in GitHub Desktop.
drawText(text, options) {
const context = this.context;
const { baseline, color, font, position, stroke } = options;
if (!text.length || text.constructor !== String) {
throw new Error(
'Text must be a string with at least one character'
);
}
if (!position || position.constructor !== Object) {
throw new Error(
'Position must be supplied in options as an object containing "left" and "top" properties'
);
}
if (font) {
context.font = font;
}
if (baseline) {
context.textBaseline = baseline;
}
if (color) {
context.fillStyle = color;
}
if (stroke) {
context.lineWidth = stroke.width;
context.strokeStyle = stroke.color;
context.strokeText(text, position.left, position.top);
} else {
context.fillText(text, position.left, position.top);
}
return this;
}
@davetayls
Copy link

davetayls commented Mar 22, 2018

Object.assign(context, {
  font,
  textBaseline: baseline,
  fillStyle: color,
  lineWidth: stroke ? stroke.width : context.lineWidth,
  strokeStyle: stroke ? stroke.color : context.strokeStyle
})

if (stroke) {
  context.strokeText(text, position.left, position.top);
} else {
  context.fillText(text, position.left, position.top);
}

@alexmccabe
Copy link
Author

Ohh clap clap!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment