Chart.js标签中的HTML [英] HTML in Chart.js labels

查看:175
本文介绍了Chart.js标签中的HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如您所见,HTML未在标签内解析。有没有办法在图表的标签中显示工作图像和/或链接?

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?

推荐答案

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

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.

一种可能的选择是考虑修改Chart.js代码以使用< foreignObject> (参见<关于MDN和这篇文章//robert.ocallahan.org/2011/11/drawing-dom-content-to-canvas.htmlrel =nofollow>这个基于它。例如:

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

(大部分代码都是演示文稿的直接副本这里,只需修改为接受标签字符串并替换现有的Chart.js x标签绘图代码。)

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

这篇关于Chart.js标签中的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆