工具提示/传奇中的Chart.js标签颜色定位

时间:2019-06-12 13:16:38

标签: chart.js ng2-charts

设计人员决定使用漂亮的标准Doghnut图表,但带有一些非标准的工具提示/图例。 See here

使用chart.js上下文填充该文本,中间的文本不是问题。当涉及到图例和工具提示时,事情会变得混乱。

对于工具提示,我尝试使用标题回调来放置粗体文本,并使用标签回调能够创建文本,但是这里要注意的是标签颜色。实际上,它的形状是正方形,并在标题下,并且我没有找到任何配置可以放在侧面和/或使其变大。

关于图例,我发现的唯一配置是将颜色设置为“点样式”或将其放置在其他位置。

有什么好的方法来获得理想的结果吗?

我实际上也正在使用ng2-charts,我知道它有一些可以完成工作的“ monkey-patch”文件,但是如果不真正了解chart.js的内部结构,我将无法完全了解它的作用和/或如何工作可以在不更改依赖源代码的情况下对其进行编辑

1 个答案:

答案 0 :(得分:0)

--- Diclaimer:下面的许多代码都是从chart.js粘贴而来,只有很少的更改。 Chart.js代码受MIT许可,如果您打算使用它,请参考该许可---

找到了实现方法,尽管这可能不是最好和/或最可重用的方法。

对于图例,图例本身是chart.js源代码中的一个插件。因此,我只是这样简单地覆盖了插件逻辑:

const defaults = Chart.defaults;
const Element = Chart.Element;
const helpers = Chart.helpers;
const layouts = Chart.layouts;

const columnLegendPlugin = {
id: 'column-legend',

beforeInit: function (chart) {
    this.stash_draw = chart.legend.draw;
    chart.legend.draw = function () {
        const me = chart.legend;
        const opts = me.options;
        const labelOpts = opts.labels;
        const globalDefaults = defaults.global;
        const defaultColor = globalDefaults.defaultColor;
        const lineDefault = globalDefaults.elements.line;
        const legendHeight = me.height;
        const columnHeights = me.columnHeights;
        const legendWidth = me.width;
        const lineWidths = me.lineWidths;

        if(opts.display) {
            const ctx = me.ctx;
            const fontColor = helpers.valueOrDefault(labelOpts.fontColor, globalDefaults.defaultFontColor);
            const labelFont = helpers.options._parseFont(labelOpts);
            const fontSize = labelFont.size;
            let cursor;

            // Canvas setup
            ctx.textAlign = 'left';
            ctx.textBaseline = 'middle';
            ctx.lineWidth = 0.5;
            ctx.strokeStyle = fontColor; // for strikethrough effect
            ctx.fillStyle = fontColor; // render in correct colour
            ctx.font = labelFont.string;

            const boxWidth = getBoxWidth(labelOpts, fontSize);
            const hitboxes = me.legendHitBoxes;

            // current position
            const drawLegendBox = function (x, y, legendItem) {
                if(isNaN(boxWidth) || boxWidth <= 0) {
                    return;
                }

                // Set the ctx for the box
                ctx.save();

                const lineWidth = helpers.valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth);
                ctx.fillStyle = helpers.valueOrDefault(legendItem.fillStyle, defaultColor);
                ctx.lineCap = helpers.valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle);
                ctx.lineDashOffset = helpers.valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset);
                ctx.lineJoin = helpers.valueOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle);
                ctx.lineWidth = lineWidth;
                ctx.strokeStyle = helpers.valueOrDefault(legendItem.strokeStyle, defaultColor);

                if(ctx.setLineDash) {
                    // IE 9 and 10 do not support line dash
                    ctx.setLineDash(helpers.valueOrDefault(legendItem.lineDash, lineDefault.borderDash));
                }

                if(labelOpts && labelOpts.usePointStyle) {
                    // Recalculate x and y for drawPoint() because its expecting
                    // x and y to be center of figure (instead of top left)
                    const radius = boxWidth * Math.SQRT2 / 2;
                    const centerX = x + boxWidth / 2;
                    const centerY = y + fontSize / 2;

                    // Draw pointStyle as legend symbol
                    helpers.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
                } else {
                    // Draw box as legend symbol
                    ctx.fillRect(x, y, boxWidth, Math.min(fontSize, labelOpts.boxHeight));
                    if(lineWidth !== 0) {
                        ctx.strokeRect(x, y, boxWidth, Math.min(fontSize, labelOpts.boxHeight));
                    }
                }

                ctx.restore();
            };
            const fillText = function (x, y, legendItem, textWidth) {
                const halfFontSize = fontSize / 2;
                const xLeft = /* boxWidth + halfFontSize + */ x;
                //const yMiddle = y + halfFontSize;

                const yMiddle = y + labelOpts.yShift;

                if(legendItem.text && legendItem.text.length > labelOpts.maxLabelLength) {
                    legendItem.text = (legendItem.text as string).slice(0, labelOpts.maxLabelLength) + '.';
                }

                ctx.fillText(legendItem.text, xLeft, yMiddle);

                if(legendItem.hidden) {
                    // Strikethrough the text if hidden
                    ctx.beginPath();
                    ctx.lineWidth = 2;
                    ctx.moveTo(xLeft, yMiddle);
                    ctx.lineTo(xLeft + textWidth, yMiddle);
                    ctx.stroke();
                }
            };

            const alignmentOffset = function (dimension, blockSize) {
                switch(opts.align) {
                    case 'start':
                        return labelOpts.padding;
                    case 'end':
                        return dimension - blockSize;
                    default: // center
                        return (dimension - blockSize + labelOpts.padding) / 2;
                }
            };

            // Horizontal
            const isHorizontal = me.isHorizontal();
            if(isHorizontal) {
                cursor = {
                    x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
                    y: me.top + labelOpts.padding,
                    line: 0
                };
            } else {
                cursor = {
                    x: me.left + labelOpts.padding,
                    y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
                    line: 0
                };
            }

            const itemHeight = fontSize + labelOpts.padding;
            helpers.each(me.legendItems, function (legendItem, i) {
                const textWidth = Math.min(ctx.measureText(legendItem.text).width, 100);
                const width = boxWidth + (fontSize / 2) + textWidth;
                let x = cursor.x;
                let y = cursor.y;

                // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
                // instead of me.right and me.bottom because me.width and me.height
                // may have been changed since me.minSize was calculated
                if(isHorizontal) {
                    if(i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
                        y = cursor.y += itemHeight;
                        cursor.line++;
                        x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
                    }
                } else if(i > 0 && y + itemHeight > me.top + me.minSize.height) {
                    x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
                    cursor.line++;
                    y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
                }

                drawLegendBox(x, y, legendItem);

                hitboxes[i].left = x;
                hitboxes[i].top = y;
                hitboxes[i].height = labelOpts.yShift + labelOpts.boxHeight + labelOpts.fontSize;
                hitboxes[i].width = Math.max(Math.min(ctx.measureText(legendItem.text).width, 100), boxWidth);

                // Fill the actual label
                fillText(x, y, legendItem, textWidth);

                if(isHorizontal) {
                    cursor.x += width + labelOpts.padding;
                } else {
                    cursor.y += itemHeight;
                }
            });
        }
    };
  }
};

如果您需要使用旧的图例,只需实现一个逻辑以重用隐藏的函数,则此代码就可以正常工作。

工具提示很难处理,因为它们是核心功能,几乎没有导出API。但是您可以覆盖原型,重新使用chart.js中的代码:

const defaults = Chart.defaults;
const Element = Chart.Element;
const helpers = Chart.helpers;
const layouts = Chart.layouts;

function getAlignedX(vm, align) {
    return align === 'center'
    ? vm.x + vm.width / 2
    : align === 'right'
        ? vm.x + vm.width - vm.xPadding
        : vm.x + vm.xPadding;
}

export const niceTooltipPlugin = {
id: 'nice-tooltip-plugin',

beforeInit: function (chart) {
    Chart.Tooltip.prototype.draw = function () {
        const ctx = this._chart.ctx;
        const vm = this._view;

        if(vm.opacity === 0) {
            return;
        }

        const tooltipSize = {
            width: Math.max(vm.width, ctx.measureText(vm.body[0].lines[0].tooltipLabel).width + 50, ctx.measureText(vm.body[0].lines[0].tooltipData).width + 50),
            height: 1.5 * vm.height
        };
        const pt = {
            x: vm.x,
            y: vm.y
        };

        const opacity = vm.opacity;

        // Truthy/falsey value for empty tooltip
        const hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;

        if(this._options.enabled && hasTooltipContent) {
            ctx.save();
            ctx.globalAlpha = opacity;

            // Draw Background
            this.drawBackground(pt, vm, ctx, tooltipSize);

            // Draw Title, Body, and Footer
            pt.y += vm.yPadding;

            // Titles
            this.drawTitle(pt, vm, ctx);

            // Body
            this.drawBody(pt, vm, ctx);

            // Footer
            this.drawFooter(pt, vm, ctx);

            ctx.restore();
        }
    };

    Chart.Tooltip.prototype.drawBody = function (pt, vm, ctx) {
        const bodyFontSize = vm.bodyFontSize;
        const bodySpacing = vm.bodySpacing;
        const bodyAlign = vm._bodyAlign;
        const body = vm.body;
        const drawColorBoxes = vm.displayColors;
        const labelColors = vm.labelColors;
        let xLinePadding = 0;
        const colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
        let textColor;

        ctx.textAlign = bodyAlign;
        ctx.textBaseline = 'top';
        ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);

        pt.x = getAlignedX(vm, bodyAlign);

        // Before Body
        const fillLineOfText = function (line) {
            ctx.fillText(line, pt.x + xLinePadding, pt.y);
            pt.y += bodyFontSize + bodySpacing;
        };

        // Before body lines
        ctx.fillStyle = vm.bodyFontColor;
        helpers.each(vm.beforeBody, fillLineOfText);

        xLinePadding = drawColorBoxes && bodyAlign !== 'right'
            ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
            : 0;

        // Draw body lines now
        helpers.each(body, function (bodyItem, i) {
            textColor = vm.labelTextColors[i];
            ctx.fillStyle = textColor;
            helpers.each(bodyItem.before, fillLineOfText);

            helpers.each(bodyItem.lines, function (line) {
                // Draw Legend-like boxes if needed
                if(drawColorBoxes) {
                    /* // Fill a white rect so that colours merge nicely if the opacity is < 1
                    ctx.fillStyle = vm.legendColorBackground;
                    ctx.fillRect(colorX, pt.y, bodyFontSize, bodyFontSize);

                    // Border
                    ctx.lineWidth = 1;
                    ctx.strokeStyle = labelColors[i].borderColor;
                    ctx.strokeRect(colorX, pt.y, bodyFontSize, bodyFontSize);

                    // Inner square
                    ctx.fillStyle = labelColors[i].backgroundColor;
                    ctx.fillRect(colorX + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
                    ctx.fillStyle = textColor; */
                    ctx.fillStyle = labelColors[i].backgroundColor;
                    helpers.canvas.drawPoint(ctx, undefined, 5, pt.x, pt.y + 12, 360);
                    ctx.fillStyle = textColor;
                }

                ctx.font = helpers.fontString(bodyFontSize, "bold", vm._bodyFontFamily);
                fillLineOfText(line.tooltipLabel);
                ctx.font = helpers.fontString(bodyFontSize, "normal", vm._bodyFontFamily);
                ctx.fillStyle = "#b0b0b0";
                fillLineOfText(line.tooltipData);
                ctx.fillStyle = textColor;
            });

            helpers.each(bodyItem.after, fillLineOfText);
        });
    };
 }
};