Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="wrapper">
  <canvas id="chart" width="300" height="300">
    Canvas not supported ...
  </canvas>
</div>
<div class="chartSelect">
  <input type="radio" id="cs_week" name="cs_radio" value="week" onchange="drawChart(this.value)" checked>
  <label for="cs_week">Week</label>
  <input type="radio" id="cs_month" name="cs_radio" value="month" onchange="drawChart(this.value)">
  <label for="cs_month">Month</label>
</div>

              
            
!

CSS

              
                * {
	-webkit-tap-highlight-color: rgba(0,0,0,0);
	-webkit-touch-callout: none;
	user-select: none;
}
body {
  margin: 0;
  padding: 0;
}
.wrapper {
  margin: 10px;
  padding: 20px;
  width: 300px;
  height: 300px;  
  border: solid 1px #ccc;
}
.chartSelect {
  margin: 10px;
  padding: 10px;
  width: 320px;
  border: solid 1px #ccc;
  line-height: 1;
}
input[type="radio"], label {
  cursor: pointer;  
}
#cs_month {
  margin-left: 10px;
}

              
            
!

JS

              
                const RECORD = [
  {y: 2018, M: 6, d: 8},   // mon 7/2 ... 1
  {y: 2018, M: 6, d: 9},   // mon 7/9 ... 3
  {y: 2018, M: 6, d: 10},
  {y: 2018, M: 6, d: 11},
// 7/16 ... 0
// 7/23 ... 0
// 7/30 ... 0

  {y: 2018, M: 7, d: 8},   // mon 8/6 ... 2
  {y: 2018, M: 7, d: 12},

  {y: 2018, M: 7, d: 19},  // mon 8/13 ... 1
  
  {y: 2018, M: 7, d: 20},  // mon 8/20 ... 7
  {y: 2018, M: 7, d: 21},
  {y: 2018, M: 7, d: 22},
  {y: 2018, M: 7, d: 23},
  {y: 2018, M: 7, d: 24},
  {y: 2018, M: 7, d: 25},
  {y: 2018, M: 7, d: 26},
                          // mon 8/27 ... 0
  {y: 2018, M: 8, d: 3},  // mon 9/3 ... 6
  {y: 2018, M: 8, d: 4},
  {y: 2018, M: 8, d: 5},
  {y: 2018, M: 8, d: 6},
  {y: 2018, M: 8, d: 7},
  {y: 2018, M: 8, d: 8},
  {y: 2018, M: 8, d: 10}, // mon 9/10 ... 4
  {y: 2018, M: 8, d: 11},
  {y: 2018, M: 8, d: 13},
  {y: 2018, M: 8, d: 14},
];

/*
const RECORD = [
//  {y: 2018, M: 7, d: 5},
//  {y: 2018, M: 7, d: 6},
//  {y: 2018, M: 8, d: 5},
//  {y: 2018, M: 8, d: 14},
];
*/

//const now = moment();
//RECORD.push({y: now.year(), M: now.month(), d: now.date()});

// 4月50%
const __RECORD =[];
const __start = moment([2018,3,1]);
const __days = __start.daysInMonth() / 2;
for (let i=1; i<=__days; i++) {
  __RECORD.push({y: 2018, M: 3, d: i});
}
RECORD.unshift(...__RECORD);


// 2月100%
const _RECORD =[];
const _start = moment([2018,1,1]);
const _days = _start.daysInMonth();
for (let i=1; i<=_days; i++) {
  _RECORD.push({y: 2018, M: 1, d: i});
}
RECORD.unshift(..._RECORD);



const ARIS = {
//  data: [],
//  label: [],
//  options: [],
  chart: null,
};


function drawChart(type) {
  const CHARTDATA = createChartData(type);
  const OPTIONS = createChartOptions(type, CHARTDATA.xRng);

  if (ARIS.chart) {
    ARIS.chart.data.labels = CHARTDATA.label;
    ARIS.chart.data.datasets[0].data = CHARTDATA.data;
    ARIS.chart.data.datasets[0].backgroundColor = getColor(type, 0.8);
    ARIS.chart.options = OPTIONS;
    Chart.defaults.global.defaultFontColor = getColor(type, 1);
    ARIS.chart.update();
  } else {
    const CTX = document.getElementById('chart').getContext('2d');
    ARIS.chart = new Chart(CTX, {
      type: "bar",
      data: {
        labels: CHARTDATA.label,
        datasets: [{
          data: CHARTDATA.data,
          backgroundColor: getColor(type, 0.8),
          borderWidth: 0,
        }]    
      },
      options: OPTIONS
    });
    Chart.defaults.global.defaultFontColor = getColor(type, 1);
  }
}

function getColor(type, a) {
  let color;
  switch (type) {
    case "week": color = `rgba(255, 165, 0, ${a})`; break;
//    case "month": color = `rgba(255, 69, 0, ${a})`; break;
    case "month": color = `rgba(255, 20, 147, ${a})`; break;
    default: color = `rgba(0, 0, 0, ${a})`; break;
  }
  return color;
}

function createChartOptions(type, xRng) {
  let yaxes_min, yaxes_max, yaxes_stepsize, yaxes_callback;
  let xaxes_unit, xaxes_formats_week, xaxes_formats_month, xaxes_isoweekday;
  let title_text;

  switch (type) {
    case "week":
      yaxes_min = 0;
      yaxes_max = 7;
      yaxes_stepsize = 1;
      yaxes_callback = (value) => value;

      xaxes_unit = "week";
      xaxes_formats_week = "M/D";
      xaxes_formats_month = "";
      xaxes_isoweekday = true;
 
      title_text = "Weekly aggregate";
      break;
    case "month":
      yaxes_min = 0;
      yaxes_max = 100;
      yaxes_stepsize = 25;
      yaxes_callback = (value) => `${value}%`;

      xaxes_unit = "month";
      xaxes_formats_week = "";
      xaxes_formats_month = "M";
      xaxes_isoweekday = false,

      title_text = "Monthly aggregate";
      break;
    default:
      break;
  }

  const OPT = {
    scales: {
      yAxes: [{
        ticks: {
          min: yaxes_min,
          max: yaxes_max,
          stepSize: yaxes_stepsize,
          callback: yaxes_callback
        },
        gridLines: {
          color: getColor(type, 0.4),
          zeroLineColor: getColor(type, 0.8)
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: xaxes_unit,
          displayFormats: {
            week: xaxes_formats_week,
            month: xaxes_formats_month
          },
          isoWeekday: xaxes_isoweekday,
          min: xRng.cmin,
          max: xRng.max
        },
        ticks: {
          source: 'labels',
          maxRotation: 0
        },
        gridLines: {
          display: false,
        }
      }]
    },    
    title: {
      display: true,
      text: title_text,
      fontSize: 14,
      position: 'top',
      padding: 12
    },
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    pan: {
      enabled: true,
      mode: "x",
      speed: 10,
      threshold: 10,
      rangeMin: {
        x: xRng.rmin
      },
      rangeMax: {
        x: xRng.max
      },
    },
    zoom: {
      enabled: true,  // panのときもtrueにしないといけない
      mode: ""
    },
    hover: {
      mode: ""    // disable
    }
  };
  return OPT;
}

function createChartData(type) {
  const LEN = RECORD.length;
//  console.log(`len: ${LEN}`);
  const SHOWRANGE = 6;    // canvasに表示するデータ数

  let rmin, cmin, max;
  let num, unit, ofs;
  let pushData;

  /***
   * x axes: unix timestamp
   * rmin ----- cmin ===== max
   *              | canvas  |
   *  |        record       |
   **/
  switch (type) {
    case "week":
      rmin = moment(RECORD[0]).startOf("isoWeek"),   // 最も古い(先頭の)記録
      cmin = moment().startOf("isoWeek").add(-SHOWRANGE, "w"), // 表示する範囲
      max = moment().startOf("isoWeek")  // 現在の日付

      num = max.diff(rmin, "weeks");
      unit = "w";
      ofs = 3.5*24*60*60*1000;   // 時間軸のオフセット(表示用:一週間の半分)
      pushData = (count) => {DATA.push(count)};
      break;
    case "month":
      rmin = moment(RECORD[0]).startOf("month"),
      cmin = moment().startOf("month").add(-SHOWRANGE, "M"),
      max = moment().startOf("month")

      num = max.diff(rmin, "months");
      unit = "M";
      ofs = (max.daysInMonth()/2)*24*60*60*1000;   // 時間軸のオフセット(表示用:月の半分)
      pushData = (count) => {
        const days = moment(LABEL[LABEL.length-1]).daysInMonth();
        DATA.push((count/days)*100);
      };
      break;
    default:
      break;
  }

  console.log(`rmin: ${rmin.format('L')}`);
  console.log(`cmin: ${cmin.format('L')}`);
  console.log(`max:  ${max.format('L')}`);

  console.log(`num: ${num}`);

  // setting of start data
  let start;
  if (num < SHOWRANGE) {   // データ数がSHOWRANGEに満たない場合
    num = SHOWRANGE;       // 回数0のデータを追加してSHOWRANGE分のデータを作成する
    rmin = cmin;      // rangeMinがcanvas内にあってもpanできてしまう
    start = cmin.clone();  // 先頭データを現在からSHOWRANGE分前にする
  } else {
    start = rmin.clone();  // 先頭データを最初の記録にする
  }

  /***
   * note:
   * moment(undefined) === moment()
   **/  

  // Aggregate
  const LABEL = [], DATA = [];
  let count = 0;
  let recIdx = 0;
  for (let i=0; i<num; i++) {
    LABEL.push(start.valueOf());
    const endValue = start.add(1, unit).valueOf();   // Increment start object

    for (; recIdx<LEN; recIdx++) {
      if (moment(RECORD[recIdx]).valueOf() < endValue) {
        count++;
      } else {
        pushData(count);
        count = 0;
        break;
      }
    }
    if (recIdx === LEN) {
      pushData(count);
      count = 0;
    }
  }

  return {
    label: LABEL,
    data: DATA,
    xRng: {
      rmin: rmin.valueOf() - ofs,
      cmin: cmin.valueOf() - ofs,
      max: max.valueOf() - ofs
    }
  };
}

window.onload = () => {
  drawChart("week");
};
              
            
!
999px

Console