canvas example

messing with canvas

HTML

<canvas id="canvas" width="500" height="200">This text is displayed if your browser does not support HTML5 Canvas.</canvas>

<div>
  <label>Active Date Value: <span id="dateValue">1</span></label>
  <button id="opt1">2016 JAN 1</button>
  <button id="opt2">JAN 1</button>
  <button id="opt3">¯\_(ツ)_/¯</button>
</div>

<div>
  <span>Number of Spaces:</span>
  <input id="spaces" type="number" value="-27" />
</div>

<div>
  <label>Line Markers: <input id="markers" type="checkbox" checked="checked" /></label>
</div>

CSS

canvas {
    border: 2px solid;
}
label{
  padding-top: 20px;
  display: block;
}
div{
  padding-top:15px;
}

Babel + JSX

let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let dateText = '¯\_(ツ)_/¯';

let useMarkers = true;
  
const fontHeight = 24;
context.font = fontHeight + 'px Calibri';
context.textBaseline = 'top';

const DATE_REGEX = /\d{4} \w{3} \d{1,2}$/;
const MONTH_REGEX = /\w{3} \d{1,2}$/;
const DAY_REGEX = /\d{1,2}$/;

const {width, height} = context.canvas;
const halfHeight = height / 2;
const pinnedText = '2016 DEC 31';
const [y, m, d] = pinnedText.split(' ');
const {width: singleCharPadding} = context.measureText(' ');
const {width: yearWidth} = context.measureText(y);
const {width: monthWidth} = context.measureText(`${y} ${m}`);
const {width: dayWidth} = context.measureText(`${y} ${m} ${d}`);

let textPadding = singleCharPadding * 2;
let maxTextWidth = dayWidth + textPadding;

const maxTextPadding = 20;
const bottomLine = halfHeight + 30;
const topLine = halfHeight;
const lineText = bottomLine + 10;

let mouse = {
	x: NaN,
  y: NaN
};

function drawDateText (text) {
	let {width: textW} = context.measureText(text);
  let halfTextW = textW / 2;
  const mouseX = mouse.x;
	context.textAlign = 'center';
	context.fillStyle = 'black';
  context.lineWidth = 1;
  
  // pad max
  if (mouseX <= maxTextWidth + maxTextPadding + halfTextW) {
    if (DATE_REGEX.test(text)) {
			let [dateText] = DATE_REGEX.exec(pinnedText) || [];
      const startPos = 0;
      const endPos = dayWidth;
      handleTextOverlap(text, mouseX, dateText, startPos, endPos, halfTextW);
      
    } 
    else if (MONTH_REGEX.test(text)) {
      let [monthText] = MONTH_REGEX.exec(pinnedText) || [];
      const startPos = yearWidth + singleCharPadding;
      const endPos = dayWidth;
      handleTextOverlap(text, mouseX, monthText, startPos, endPos, halfTextW);
    }
    else if (DAY_REGEX.test(text)) {
    	let [dayText] = DAY_REGEX.exec(pinnedText) || [];
      const startPos = monthWidth + singleCharPadding;
      const endPos = dayWidth;
      handleTextOverlap(text,...