简体   繁体   English

画布/ JavaScript:如何使用画布调整甜甜圈图中的切片位置?

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

I am trying to draw a donut pie chart using Canvas. 我正在尝试使用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. http://jsfiddle.net/RgLAU/1/我想要1.)黄色/蓝色从顶部绘制2.)想在甜甜圈内写一些文本。 Here is my work upto now: 这是我到目前为止的工作:

http://jsfiddle.net/RgLAU/1/ 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. arc()方法从形状右侧的水平线开始,在形状高度的中间y位置。

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. 对于您的文本,我不确定应该显示什么内容,但是设置上下文的textAlign = "center"textBaseline = "middle"将使它易于放置在任何地方。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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