Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Created July 27, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/2effa73c277eef458c84 to your computer and use it in GitHub Desktop.
Save Cartman0/2effa73c277eef458c84 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 {
background-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, 50, 70, 100, 130, 200, 250];
var line_opts = {
color: 'red',
width: 2
};
var dot_opts = {
color: 'black',
radius: 2
};
var text_opts = {
color: 'green',
font: "12px 'san-serif', 'Arial'",
// テキストの行揃え
textAlign: 'center',
// テキストのベースライン
textBaseline: 'top'
}
lineGraph(canvas1, datas, line_opts, dot_opts, text_opts);
function lineGraph(canvas_obj, datas, line_opts, dot_opts, text_opts){
var c = canvas_obj.getContext('2d');
// line
var pos1 = {
x: 0,
y: canvas_obj.height
};
var pos2 = {
x: 0,
y: 0
};
var dataWH = {
w: canvas_obj.width / datas.length,
h: canvas_obj.height
};
for (var i = 0; i < datas.length; i++){
line(c, datas[i], dataWH, line_opts, dot_opts, text_opts);
}
function line(context, data, dataWH, line_opts, dot_opts, text_opts){
context.save();
context.strokeStyle = line_opts.color;
context.lineWidth = line_opts.width;
context.beginPath();
context.moveTo(pos1.x, pos1.y);
pos2.x += dataWH.w;
pos2.y = dataWH.h - data;
context.lineTo(pos2.x, pos2.y);
context.stroke();
//pos1更新
pos1 = pos2;
context.restore();
//点
context.save();
context.fillStyle = dot_opts.color;
context.moveTo(pos2.x, pos2.y);
context.arc(pos2.x, pos2.y, dot_opts.radius, 0, 2 * Math.PI);
context.fill();
context.restore();
//数値
context.save();
context.fillStyle = text_opts.color;
context.font = text_opts.font;
// テキストの行揃え
context.textAlign = text_opts.textAlign;
// テキストのベースライン
context.textBaseline = text_opts.textBaseline;
context.fillText(data, pos2.x, pos2.y);
context.restore();
}
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment