图表标签文字旋转

时间:2013-01-24 10:12:23

标签: html5 canvas graph html5-canvas

我使用非常相似的代码根据本文使用canvas创建饼图:

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

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

enter image description here

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

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();

};

我正在努力纠正这个问题,所以文字总是可读的而不是颠倒的,但是无法解决这个问题!

2 个答案:

答案 0 :(得分:2)

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

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();
};

答案 1 :(得分: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();
};