我想绘制具有不同颜色和半径的扇区。所以我使用canvas.arc和fill方法编写了一些代码
// constants & vars
var data=[0.2, 0.5, .5, 1.0, 0.8, .9, .7, .8];
var colors=["red", "blue", "green", "gray", "orange",
"rgb(255,165,0)", "rgb(100,100,100)", "black"];
var WIDTH = 200;
var HEIGHT = 200;
var centralPoint = {x:WIDTH/2, y:HEIGHT/2};
var radius=HEIGHT/2;
var sectorsCount = data.length;
var epsilon=0.0001;
var myCanvas = document.getElementById("graphic"),
ctx = myCanvas.getContext('2d');
myCanvas.height=HEIGHT;
myCanvas.width=WIDTH;
//drawing
for (var i=0; i<sectorsCount-1;i++) {
ctx.moveTo(centralPoint.x, centralPoint.y);
ctx.fillStyle=colors[i];
ctx.arc(centralPoint.x,centralPoint.y,
radius*data[i],
i*2*Math.PI/sectorsCount+epsilon ,
(i+1)*2*Math.PI/sectorsCount-epsilon,
false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
ctx.fillStyle="black";
ctx.arc(centralPoint.x,centralPoint.y, 10, 0, Math.PI*2, true);
ctx.fill();
问题是下一个扇区在绘制时,上一个也要更改颜色。所以最后我得到了半径不同但颜色相同(最后)的扇区。
可能有更简单的方法来做同样的事情?
最佳答案
路径绘制命令以context.beginPath
开头,并一直有效,直到下一个context.beginPath
。因此,如果没有新的beginPath,则所有先前的楔形都将与最后一个楔形一起重绘。
因此,简单的解决方法是确保每个楔形以beginPath
开头:
var data=[0.2, 0.5, .5, 1.0, 0.8, .9, .7, .8];
var colors=["red", "blue", "green", "gray", "orange", "rgb(255,165,0)", "rgb(100,100,100)", "black"];
var WIDTH = 200;
var HEIGHT = 200;
var centralPoint = {x:WIDTH/2, y:HEIGHT/2};
var radius=HEIGHT/2;
var sectorsCount = data.length;
var epsilon=0.0001;
var myCanvas = document.getElementById("graphic"),
ctx = myCanvas.getContext('2d');
myCanvas.height=HEIGHT;
myCanvas.width=WIDTH;
//drawing
for (var i=0; i<sectorsCount-1;i++) {
ctx.beginPath();
ctx.moveTo(centralPoint.x, centralPoint.y);
ctx.fillStyle=colors[i];
ctx.arc(centralPoint.x,centralPoint.y,
radius*data[i],
i*2*Math.PI/sectorsCount+epsilon ,
(i+1)*2*Math.PI/sectorsCount-epsilon,
false);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
ctx.fillStyle="black";
ctx.beginPath();
ctx.arc(centralPoint.x,centralPoint.y, 10, 0, Math.PI*2, true);
ctx.fill();
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="graphic" width=300 height=300></canvas>