Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - HTML in Chart.js labels

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...