HTML in Chart.js labels

后端 未结 1 1827
盖世英雄少女心
盖世英雄少女心 2020-12-17 21:24

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\', \'Febr         


        
相关标签:
1条回答
  • 2020-12-17 22:03

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

    0 讨论(0)
提交回复
热议问题