0

根据本文,我正在使用非常相似的代码使用画布创建饼图:

http://wickedlysmart.com/how-to-make-a-pie-chart-with-html5s-canvas/

从这张图片中可以看出,有些情况下标签是颠倒的:

在此处输入图像描述

以下是将标签写入图表的代码:

var drawSegmentLabel = function(canvas, context, i) {

        context.save();
        var x = Math.floor(canvas.width / 2);
        var y = Math.floor(canvas.height / 2);
        var degrees = sumTo(data, i);

        var angle = degreesToRadians(degrees);

        context.translate(x, y);
        context.rotate(angle);
        context.textAlign = 'right';
        var fontSize = Math.floor(canvas.height / 32);
        context.font = fontSize + 'pt Helvetica';

        var dx = Math.floor(canvas.width * 0.3) - 20;
        var dy = Math.floor(canvas.height * 0.05);
        context.fillText(labels[i], dx, dy);

        context.restore();

};

我正在尝试纠正这一点,因此文本始终是可读的,而不是颠倒的,但无法弄清楚如何做到这一点!

4

2 回答 2

2

这是我的解决方案!(有点笨拙,但似乎可以在基本示例上工作,我还没有在边缘情况下进行测试......)

var drawSegmentLabel = function(canvas, context, i) {

    context.save();
    var x = Math.floor(canvas.width / 2);
    var y = Math.floor(canvas.height / 2);
    var angle;
    var angleD = sumTo(data, i);
    var flip = (angleD < 90 || angleD > 270) ? false : true;

    context.translate(x, y);
    if (flip) {
        angleD = angleD-180;
        context.textAlign = "left";
        angle = degreesToRadians(angleD);
        context.rotate(angle);
        context.translate(-(x + (canvas.width * 0.5))+15, -(canvas.height * 0.05)-10);
    }
    else {
        context.textAlign = "right";
        angle = degreesToRadians(angleD);
        context.rotate(angle);
    }
    var fontSize = Math.floor(canvas.height / 25);
    context.font = fontSize + "pt Helvetica";

    var dx = Math.floor(canvas.width * 0.5) - 10;
    var dy = Math.floor(canvas.height * 0.05);
    context.fillText(labels[i], dx, dy);

    context.restore();
};
于 2013-02-07T03:02:39.773 回答
0

要以正确的方式显示文本,您必须检查旋转角度是否在 90 到 270 度之间。如果是,那么您知道文本将颠倒显示。

要正确切换它,您必须旋转平面旋转的画布 - 180 度,然后将其左对齐而不是右对齐:

var drawSegmentLabel = function(canvas, context, i) {

    context.save();
    var x = Math.floor(canvas.width / 2);
    var y = Math.floor(canvas.height / 2);
    var degrees = sumTo(data, i);

    var angle = 0;
    if (degree > 90 && degree < 270)
      angle = degreesToRadians(degrees - 180);       
     else
       angle = degreesToRadians(degrees);

    context.translate(x, y);
    context.rotate(angle);
    context.textAlign = 'right';
    var fontSize = Math.floor(canvas.height / 32);
    context.font = fontSize + 'pt Helvetica';

    var dx = Math.floor(canvas.width * 0.3) - 20;
    if (degree > 90 && degree < 270)
       dx =  20;
    var dy = Math.floor(canvas.height * 0.05);
    context.fillText(labels[i], dx, dy);

    context.restore();
};
于 2013-01-24T10:20:43.690 回答