HTML5 Game - Chart Pie Chart

Description

Pie Chart

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
window.onload = function() {//from  w  ww. j ava 2  s.  c  o m
    let canvas = document.getElementById("myCanvas");
    let context = canvas.getContext("2d");
    // draw stuff here
    let sectorNames = Array();
    let sectorValues = Array();
    let sectorColors = Array();

    context.save();
    let linearGradient = context.createLinearGradient(0, 0, canvas.width, canvas.height);
    linearGradient.addColorStop(0, 'red');
    linearGradient.addColorStop(1, 'white');
    context.fillStyle = linearGradient;
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.restore();

    context.save();
    sectorNames[0] = 'A';
    sectorValues[0] = 1;
    sectorColors[0] = 'red';


    sectorNames[1] = 'B';
    sectorValues[1] = 2;
    sectorColors[1] = 'yellow';

    sectorNames[2] = 'c';
    sectorValues[2] = 3;
    sectorColors[2] = 'blue';

    //draw title 
    context.textAlign = "center";
    context.font = "bold 30px Arial";
    context.shadowColor = "silver";
    context.shadowOffsetX = 2;
    context.shadowOffsetY = 2;
    context.fillStyle = "black";
    context.fillText('java2s.com', 300, 50);
    context.restore();

    //draw sectors 
    let total = 0;
    for (let i = 0; i < sectorValues.length; i++) {
        total += sectorValues[i];
    }
    let angle = 0;
    for (let i = 0; i < sectorValues.length; i++) {
        context.fillStyle = sectorColors[i];
        context.beginPath();
        context.moveTo(170, 250);
        context.arc(170, 250, 150, angle, angle + (Math.PI * 2 *
            (sectorValues[i] / total)), false);
        context.lineTo(170, 250);
        context.fill();
        context.stroke();
        angle += Math.PI * 2 * (sectorValues[i] / total);
    }

    //draw legends 
    let offset = 150;
    for (let i = 0; i < sectorColors.length; i++) {
        context.fillStyle = sectorColors[i];
        context.font = 'bold 12px Arial';
        context.save();
        context.shadowColor = "silver";
        context.shadowOffsetX = 2;
        context.shadowOffsetY = 2;
        context.fillRect(400, offset, 20, 15);
        context.restore();
        context.textBaseline = "middle";
        context.fillText(sectorNames[i] + ' - ' + sectorValues[i] + '%', 425, offset + 10);
        offset += 30;
    }

};
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="600" height="600"></canvas>   
  <img id='imgCanvas'/>
 </body>
</html>

Note

The code declares three global arrays-sectorNames, sectorValues, and sectorColors-for storing sector names, their values, and their colors, respectively.

Related Topics