How to draw a custom pie chart shape using createJS or HTML canvas API?

左心房为你撑大大i 提交于 2020-08-10 19:48:30

问题


I am working on building this specific shape:

The shape that need to generated

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:

  1. CreateJS to generate this kinda CreateJS (currently using)
  2. Native HTML5 canvas API
  3. Or some other library?
  4. ChartJS
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!