Last active
August 29, 2015 14:25
-
-
Save Cartman0/fcb4844f9c038333df74 to your computer and use it in GitHub Desktop.
Canvas上で円グラフ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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 = [ | |
[10, 'red'], [60, 'yellow'], [20, 'blue'], [10, 'green'] | |
]; | |
var pieChart_opts = { | |
center_x: canvas1.width/2, | |
center_y: canvas1.height/2, | |
r: canvas1.width/3 | |
}; | |
pieChart(canvas1, datas, pieChart_opts); | |
function pieChart(canvas_obj, datas, opts){ | |
var c = canvas_obj.getContext('2d'); | |
// circle | |
var pos1 = 0; | |
var pos2; | |
for(var i = 0; i < datas.length; i++){ | |
circle(c, datas[i][0], datas[i][1], opts); | |
} | |
function circle(context, ratio, color, opts) { | |
context.beginPath(); | |
context.moveTo(opts.center_x, opts.center_y); | |
pos2 = pos1 + ratio/100 * 2 * Math.PI; | |
//円 | |
context.arc(opts.center_x, opts.center_y, opts.r, pos1 - 0.5 * Math.PI, pos2 - 0.5 * Math.PI, false); | |
context.closePath(); | |
context.fillStyle = color; | |
context.fill(); | |
pos1 = pos2; | |
} | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment