canvasでグラフを描いてみる

注意

このJavaScriptは習作です。 至らない点が各所に残っている可能性があるので、参考にする際はご注意ください。

Sample

( ^ω^)おっおっお

Code

$(function(){
  var canvas = document.getElementById('test');
  if(!canvas.getContext) return;
  var ctx = canvas.getContext("2d");

  /* gradation */
  var grad  = ctx.createLinearGradient(0,0, 0,400);
  grad.addColorStop(0,'rgb(80, 80, 80)');
  grad.addColorStop(1,'rgb(0, 0, 0)');
  ctx.fillStyle = grad;
  ctx.rect(0,0, 827,400);
  ctx.fill();

  /* vertical */
  ctx.fillStyle = "rgb(255, 0, 0)";
  ctx.fillRect(25, 0, 2, 400);
  var bar = 127;
  for(i=1; i<=10; i++) {
    ctx.fillStyle = "rgb(255, 255, 255)";
    ctx.fillRect(bar, 0, 1, 375);
    bar += 100;
  }
  /* horizon */
  ctx.fillStyle = "rgb(255, 0, 0)";
  ctx.fillRect(0, 375, 827, 2);
  var line = 100;
  for(i=1; i<=10; i++) {
    ctx.fillStyle = "rgb(255, 255, 255)";
    ctx.fillRect(27, line, 800, 1);
    line += 100;
  }

  ctx.transform(1, 0, 0, -1, 0, 400);

  /* yellow graph */
  ctx.beginPath();
  ctx.strokeStyle = "rgb(255, 255, 0)";
  ctx.moveTo(27, 27); //0, 0
  var graph1 = 127;
  var graph1_val = [53,93,113,231,144,225,321,335];
  for(i=0; i<=7; i++) {
    ctx.lineTo(graph1, graph1_val[i]);
    graph1 += 100;
  }
  ctx.stroke();

  /* blue graph */
  ctx.beginPath();
  ctx.strokeStyle = "rgb(50, 50, 255)";
  ctx.moveTo(27, 275); //0, 0
  var graph1 = 127;
  var graph1_val = [200, 261, 253, 255, 321, 246, 257, 261];
  for(i=0; i<=7; i++) {
    ctx.lineTo(graph1, graph1_val[i]);
    graph1 += 100;
  }
  ctx.stroke();

  /* green graph */
  ctx.beginPath();
  ctx.strokeStyle = "rgb(0, 255, 0)";
  ctx.moveTo(27, 75); //0, 0
  var graph1 = 127;
  var graph1_val = [27, 31, 42, 52, 62, 96, 39, 57];
  for(i=0; i<=7; i++) {
    ctx.lineTo(graph1, graph1_val[i]);
    graph1 += 100;
  }
  ctx.stroke();

});

JavaScript1000本ノック トップページへ