简体   繁体   中英

Canvas/JavaScript: How to adjust position of slices in donutgraph using canvas?

I am trying to draw a donut pie chart using Canvas. Which is almost done but facing some issue in adjusting position of slices.

Current:

在此处输入图片说明

Expected:

在此处输入图片说明

enter code here

http://jsfiddle.net/RgLAU/1/ I want 1.) yellow/blue to draw from top 2.) want to write some text inside the donut. Here is my work upto now:

http://jsfiddle.net/RgLAU/1/

arc() method starts from an horizontal line, on the right of your shape, at middle y position of the shape's height.

You will need to add an offset to each of your start and end angle value.

For your text, I'm not sure what it should display, but setting the context's textAlign = "center" and textBaseline = "middle" will make it easy to position anywhere.

A rough uncleaned dump of your modified code :

 var canvas = document.getElementById("chart"); var chart = canvas.getContext("2d"); function drawdountChart(canvas) { // text options chart.textAlign = "center"; chart.textBaseline = "middle"; chart.font = "25px sans-serif"; // where is our arc start angle var offset = 1.5 * Math.PI; this.x, this.y, this.radius, this.lineWidth, this.strockStyle, this.from, this.to = null; this.set = function(x, y, radius, from, to, lineWidth, strockStyle) { this.x = x; this.y = y; this.radius = radius; this.from = from; this.to = to; this.lineWidth = lineWidth; this.strockStyle = strockStyle; } this.draw = function(data) { canvas.beginPath(); canvas.lineWidth = this.lineWidth; canvas.strokeStyle = this.strockStyle; canvas.arc(this.x, this.y, this.radius, this.from + offset, this.to + offset); canvas.stroke(); var numberOfParts = data.numberOfParts; var parts = data.parts.pt; var colors = data.colors.cs; var df = 0; for (var i = 0; i < numberOfParts; i++) { canvas.beginPath(); canvas.strokeStyle = colors[i]; canvas.arc(this.x, this.y, this.radius, df + offset, df + (Math.PI * 2) * (parts[i] / 100) + offset); canvas.stroke(); df += (Math.PI * 2) * (parts[i] / 100); } chart.fillStyle = 'white' chart.fillText('hello', this.x, this.y); } } var data = { numberOfParts: 4, parts: { "pt": [20, 30, 25, 25] }, //percentage of each parts colors: { "cs": ["red", "green", "blue", "yellow"] } //color of each part }; var drawDount = new drawdountChart(chart); drawDount.set(150, 150, 100, 0, Math.PI * 2, 30, "#fff"); drawDount.draw(data); 
 <canvas id="chart" width="500" height="500" style="background-color:black"> </canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM