2017年2月13日月曜日

開発環境

Eloquent JavaScript(Marijn Haverbeke 著、No Starch Press)のPart 2(Browser)、Chapter 16(Drawing on Canvas)、Exercises(The Pie Chart)を取り組んでみる。

Exercises(The Pie Chart)

コード(Emacs)

HTML5

<canvas width="600" height="600" id="canvas0" ></canvas>
<script src="sample2.js"></script>

JavaScript

'use strict';
let results = [
    {name: 'Satisfied', count: 1043, color: 'lightblue'},
    {name: 'Neutral', count: 563, color: 'lightgreen'},
    {name: 'Unsatisfied', count: 510, color: 'pink'},
    {name: 'No comment', count: 175, color: 'silver'}
];
let ctx = document.querySelector('#canvas0').getContext('2d'),
    total = results.reduce((sum, choice) => sum + choice.count,
                           0),
    currentAngle = - Math.PI / 2,
    center = [300, 300],
    radius = 200;


results.forEach((result) => {
    let sliceAngle = (result.count / total) * 2 * Math.PI,
        textAngle = currentAngle + sliceAngle / 2;

    ctx.beginPath();
    ctx.arc(center[0], center[1], radius,
            currentAngle, currentAngle + sliceAngle);
    currentAngle += sliceAngle;
    ctx.lineTo(center[0], center[1]);
    ctx.fillStyle = result.color;
    ctx.fill();
    ctx.font = '28px Georgia';
    ctx.fillStyle = 'black';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(result.name,
                 center[0] + radius * Math.cos(textAngle),
                 center[1] + radius * Math.sin(textAngle));
});

0 コメント:

コメントを投稿