Skip to content

Instantly share code, notes, and snippets.

@kinjouj
Created October 9, 2013 11:28
Show Gist options
  • Save kinjouj/6899778 to your computer and use it in GitHub Desktop.
Save kinjouj/6899778 to your computer and use it in GitHub Desktop.
HTML5 <canvas> javascript rendering bar and line and point chart
<html>
<head>
<script type="text/javascript" src="underscore.js"></script>
</head>
<body>
<canvas id="canvas" width="700" height="600"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var xaxis_margin = 20;
var yaxis_margin = 50;
var max_width = canvas.width - yaxis_margin;
var max_height = canvas.height - xaxis_margin;
var values = _.times(
_.random(15, 8),
function() {
return Math.ceil(_.random(100, 999) / 100) * 100;
}
);
var max_value = Math.ceil(_.max(values) / 100) * 100;
var percentage = max_value / max_height;
var bar_width = (Math.floor(max_width / values.length / 10) * 10) / 2;
context.beginPath();
context.lineWidth = 1;
context.globalAlpha = 0.5;
context.moveTo(20, 0);
context.lineTo(20, max_height);
context.lineTo(max_width, max_height);
context.stroke();
values.forEach(drawBar);
_.range(0, max_value, 100).forEach(function(num) {
// バーの高さをpercentageで割った値を更に75%の比率で縮小させているので、目盛りの位置もそれと同様に縮小させる。更にそれに
num /= percentage;
num *= 0.75;
num += 100 + yaxis_margin;
context.beginPath();
context.lineWidth = 0.5;
context.strokeStyle = '#000';
context.moveTo(15, num);
context.lineTo(25, num);
context.stroke();
});
var prevX = 0;
var prevY = 0;
function drawBar(value, count) {
var pValue = value / percentage * 0.75;
var x = count * bar_width * 2;
var y = max_height - pValue;
var top_center = x + yaxis_margin + bar_width / 2;
context.beginPath();
context.fillStyle = 'rgb(27, 188, 155)';
context.shadowColor = "#999";
context.globalAlpha = 1;
context.fillRect(x + yaxis_margin, y, bar_width, pValue);
context.beginPath();
context.moveTo(top_center, y);
context.lineTo(prevX + yaxis_margin + bar_width / 2, prevY);
context.lineWidth = 3;
context.globalAlpha = 0.2;
context.strokeStyle = "rgb(0, 0, 255)";
context.stroke();
context.beginPath();
context.fillStyle = 'rgb(255, 0, 0)';
context.globalAlpha = 1;
context.arc(top_center, y, 5, 0, Math.PI * 2, true);
context.fill();
context.beginPath();
context.fillStyle = 'rgb(255, 0, 255)';
context.fillText(value, top_center - 10, y - yaxis_margin / 2);
context.beginPath();
context.fillStyle = 'rgb(0, 0, 0)';
context.fillText(count + 1, top_center - 5, max_height + xaxis_margin);
prevX = x;
prevY = y;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment