Chart.js 标签中的 HTML

2022-01-22 00:00:00 axis-labels javascript chart.js

我想在我的图表标签中添加一些图片和/或链接.这是示例代码和 jsFiddle:

var 数据 = {标签:['一月','<s>二月</s>','<img src="http://jsfiddle.net/favicon.png">','<a href="http://jsfiddle.net/>A 链接</a>'],数据集:[{数据:[65、59、90、81]}]}var ctx = document.getElementById(myChart").getContext(2d");var myNewChart = new Chart(ctx).Bar(data);

jsFiddle 链接

如您所见,HTML 未在标签内解析.有没有办法在图表的标签中添加有效的图像和/或链接?

解决方案

看Chart.js 源代码 似乎标签是使用 fillText 命令.fillText(text, x, y [, maxWidth]) 只接受纯文本字符串,因此您的 HTML 字符串将呈现为纯文本,所有标签都将被忽略.

一种可能的选择是考虑修改 Chart.js 代码以使用 <foreignObject>(请参阅 这篇文章在 MDN 和 this 它所基于的).例如:

ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);ctx.rotate(toRadians(this.xLabelRotation)*-1);var 数据 = 数据:图像/svg+xml",+"

(大部分代码是演示的直接副本here 作者:Robert O'Callahan,简单修改为接受标签字符串并替换现有的 Chart.js x 标签绘制代码.)

I'd like to put some images and/or links in my chart's labels. Here's the example code and jsFiddle:

var data = {
    labels: ['January', '<s>February</s>',
    '<img src="http://jsfiddle.net/favicon.png">',
    '<a href="http://jsfiddle.net/">A Link</a>'],
    datasets: [{
        data: [65, 59, 90, 81]
    }]
}
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Bar(data);

jsFiddle link

As you can see, the HTML is not parsed inside labels. Is there a way to have working images and/or links in the chart's labels?

解决方案

Looking at the Chart.js source code it appears that labels are rendered using the fillText command. fillText(text, x, y [, maxWidth]) only accepts a plain text string and so your HTML string will be render as plain text and all tags will be ignored.

One possible option would be to consider modifying the Chart.js code to use a <foreignObject> (see this article on MDN and this one which it's based on). For example:

ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
ctx.rotate(toRadians(this.xLabelRotation)*-1);

var data = "data:image/svg+xml," +
    "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
        "<foreignObject width='100%' height='100%'>" +
            "<div xmlns='http://www.w3.org/1999/xhtml'>" +
                label +
            "</div>" +
        "</foreignObject>" +
    "</svg>";

var img = new Image();
img.src = data;
img.onload = function() { ctx.drawImage(img, 0, 0); }

ctx.restore();

(Much of this code is a straight copy of the demo presented here by Robert O'Callahan, simply modified to accept a label string and replace the existing Chart.js x label drawing code.)

相关文章