Draw a pie chart with canvas

Source: Internet
Author: User

<!doctype html>

lang="en">

>

<meta charset= "UTF-8" />

<title> Little Bear pie chart </title>

<meta CharSet="GBK">

<script>

//Draw pie chart

function drawcircle(canvasid, Data_arr, Color_arr, Text_arr) {

var c = document.getElementById (canvasid);

var ctx = C.getcontext ("2d");

var radius = c.height /2-20;//Radius

var ox = Radius + ,

Oy = radius + 20; //Center

var width =

Height = 10; //Legend width and height

var posX = Ox * 2 + /c10>

PosY = 30; //

var textx = PosX + width + 5,

texty = PosY + ten;

var startangle = 0; //Start radians

var endangle = 0; //End radians

For (var i = 0; I < data_arr.length; I+ +) {

//Draw pie chart

endangle = endangle + data_arr[i] * Math.PI * 2; //End radians

ctx.fillstyle = color_arr[i];

ctx.beginpath ();

ctx.moveto (Ox, OY); //Move to center

ctx.arc (Ox, Oy, radius, startangle, Endangle, false);

ctx.closepath ();

ctx.fill ();

startangle = endangle; //Set start radians

//Draw scale chart and text

ctx.fillstyle = color_arr[i];

ctx.fillrect (PosX, PosY + * I, width, height);

ctx.moveto (PosX, PosY + * i);

ctx.font = ' bold 12px Microsoft Ya Black '; //Italic 30 pixels Microsoft Jas Black font

ctx.fillstyle = color_arr[i]; //"#000000";

var percent = text_arr[i] + ":" + $ * Data_arr[i] + "% ";

ctx.filltext (Percent, TEXTX, texty + i);

}

}

function init() {

//Draw pie chart

//proportional data and colors

var data_arr = [0.2, 0.3, 0.3, 0.2];

var color_arr = ["#FFAA00", "#00AABB", "#73BF00", "#FF4400"];

var text_arr = ["NO1", "NO2", "NO3", "NO4"];

drawcircle ("Canvas_circle", Data_arr, Color_arr, Text_arr);

}

//The Init () function is executed when the page loads

window.onload = init;

</script>

>

<body>

<p>

<canvas id= "canvas_circle" width= "Max" height= " style= " Border:2px solid #5A5AAD; " >

Browser does not support canvas

</canvas>

</p>

</body>

>

Draw a pie chart with canvas

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.