Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active August 29, 2015 14:25
Show Gist options
  • Save Cartman0/89117cd015cdd5538968 to your computer and use it in GitHub Desktop.
Save Cartman0/89117cd015cdd5538968 to your computer and use it in GitHub Desktop.
Canvas上で棒グラフ
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>棒グラフ</title>
<meta name="description" content="">
<style>
body {
backgorund-color: #fafafa;
}
canvas {
display: block;
border: 1px solid #333;
background-color: #eee;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<canvas id="canvas1" width="300" height="300">
</canvas>
<script type="text/javascript">
(function(){
var canvas1 = document.getElementById('canvas1');
var datas = [20, 60, 30, 50, 100, 150, 200];
var stroke_opts = {
color: 'balck',
width: 2
};
var fill_opts = {
color: 'red'
}
barGraph(canvas1, datas, stroke_opts, fill_opts);
function barGraph(canvas_obj, datas, stroke_opts, fill_opts){
var c = canvas_obj.getContext('2d');
// bar
var pos = 0;
var bar_width = canvas_obj.width / datas.length;
for (var i = 0; i < datas.length; i++){
var barPos = {
x: pos,
y: canvas_obj.height - datas[i],
w: bar_width
};
bar(c, datas[i], barPos, stroke_opts, fill_opts);
pos += bar_width;
}
function bar(context, data, barPos, stroke_opts, fill_opts) {
context.strokeStyle = stroke_opts.color;
context.lineWidth = stroke_opts.width;
context.strokeRect(barPos.x, barPos.y, barPos.w, data);
context.fillStyle = fill_opts.color;
context.fillRect(barPos.x, barPos.y, barPos.w, data);
}
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment