问题
I am working on building this specific shape:
This kind of looks like a pie chart having 3 leaves with each leaf having 3 set of colours. Each colour represents a specific info about data which will be showing on a popup either by clicking or hovering over it based on JSON . This pie will be placed on the map based on the coordinates(Lat, Long) assigned to it. The small red circle at the center is the place for coordinates(Lat, Long).
I might use:
- CreateJS to generate this kinda CreateJS (currently using)
- Native HTML5 canvas API
- Or some other library?
- ChartJS
- 2.js
How can I go about building this? Are there any libraries that would help?
回答1:
Using CanvasRenderingContext2D.arc
The function CanvasRenderingContext2D.arc will create a circular path that you can fill. You can also do part of a circle by setting the start and end angles and which direction to draw (clock wise or counter clock wise)
To draw a pie shape, first create the outside path, in a clock wise direction, then add the inside path in a counter clock wise direction. Then just fill and you have a slice of pie.
See the link for more details on the use ofCanvasRenderingContext2D.arc
The example below use are to draw the pie chart, using the native CanvasRenderingContext2D API
const ctx = canvas.getContext('2d');
const maxRadius = Math.min(canvas.width, canvas.height) / 2;
const slices = 4, cols = [, "red", "green", "blue"], TAU = Math.PI * 2, spacing = 0.6;
const slice = TAU / slices;
const startAng = (-Math.PI - (slice * (1-spacing))) / 2;
ctx.setTransform(1,0,0,1,canvas.width / 2, canvas.height / 2); // set origin to center of canvas
var i = 0, j = 1;
while (j < cols.length) {
const outerRad = (maxRadius / cols.length) * (j + 1)
const innerRad = (maxRadius / cols.length) * j;
ctx.fillStyle = cols[j++];
i = 0;
while (i < slices) {
const ang = slice * (i++) + startAng;
ctx.beginPath();
ctx.arc(0, 0, outerRad, ang, ang + slice * (1-spacing));
ctx.arc(0, 0, innerRad, ang + slice * (1-spacing), ang,true);
ctx.fill();
}
}
<canvas id="canvas"></canvas>
来源:https://stackoverflow.com/questions/63303764/how-to-draw-a-custom-pie-chart-shape-using-createjs-or-html-canvas-api