简体   繁体   中英

Draw vertical and horizonal lines on the radar chart (like x-y axes)

Using chartjs, I would like to draw one horizontal and one vertical line that extend from the center of the radar chart and display custom title on the lines like below, can someone guide me?

在此处输入图片说明

For the benefit of other users, I drew the axes with the chartjs plugins:

            plugins: [{
                beforeDraw: function(chart, options) {
                    if (chart.config.data.drawXYAxes) {
                        var ctx = chart.chart.ctx;
                        var yaxis = chart.scales['scale'];
                        var paddingX = 100;
                        var paddingY = 40;

                        ctx.save();
                        ctx.beginPath();
                        ctx.strokeStyle = '#0000ff';
                        ctx.lineWidth = 0.75;

                        drawArrow(ctx, yaxis.xCenter, yaxis.yCenter, yaxis.xCenter - yaxis.drawingArea - paddingX, yaxis.yCenter);
                        drawArrow(ctx, yaxis.xCenter, yaxis.yCenter, yaxis.xCenter + yaxis.drawingArea + paddingX, yaxis.yCenter);
                        drawArrow(ctx, yaxis.xCenter, yaxis.yCenter, yaxis.xCenter, yaxis.yCenter - yaxis.drawingArea - paddingY);
                        drawArrow(ctx, yaxis.xCenter, yaxis.yCenter, yaxis.xCenter, yaxis.yCenter + yaxis.drawingArea + paddingY);

                        ctx.stroke();
                        ctx.restore();
                    }
                }
            }]

paddingX and paddingY allow me to show the arrows above the actual radar chart, otherwise the chart will be drawn from top position leaving no room for arrow to go little up.

drawArrow function (credit: https://stackoverflow.com/a/6333775/1624330 ) will draw the line:

drawArrow = function(context, fromx, fromy, tox, toy) {
    var headlen = 10;
    var dx = tox - fromx;
    var dy = toy - fromy;
    var angle = Math.atan2(dy, dx);
    context.moveTo(fromx, fromy);
    context.lineTo(tox, toy);
    context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6));
    context.moveTo(tox, toy);
    context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM