使用带有javascript饼图的背景图像

时间:2015-05-04 19:11:41

标签: javascript jquery canvas html5-canvas easypie

我在Rails中构建一个应用程序,我正在使用一个名为easy_as_pie的gem,它允许我使用这个名为'Easy Pie Chart'的Jquery插件(http://rendro.github.io/easy-pie-chart/

我使用以下代码使饼图工作没有问题:

$(document).ready(function() {
  $('.chart').easyPieChart({
    size: 300,
    animate: 1400,
    lineWidth: 150,
    lineCap: "butt",
    scaleColor: false,
    trackColor: "black",
    barColor: "white"
  });
});

我的问题是,是否可以让图表加载背景图像而不是纯色。在文档中,它允许您使用带有函数的渐变,使用以下代码:

new EasyPieChart(element, {
  barColor: function(percent) {
    var ctx = this.renderer.ctx();
    var canvas = this.renderer.canvas();
    var gradient = ctx.createLinearGradient(0,0,canvas.width,0);
        gradient.addColorStop(0, "#ffe57e");
        gradient.addColorStop(1, "#de5900");
    return gradient;
  }
});

我希望让渐变工作,然后尝试操作函数来加载图像。但是我甚至没有成功地使渐变起作用。

1 个答案:

答案 0 :(得分:0)

Provided your gradient example works like it looks, you should be able to draw just about anything you want into the canvas object they've provided. With that in mind, you might be able to draw images like so:

new EasyPieChart(element, {
  barColor: function(percent) {
    var ctx = this.renderer.ctx();
    var canvas = this.renderer.canvas();
    var yourImage = new Image(); 
    yourImage.src = "path-to-your-img.jpg";
    return ctx.drawImage(yourImage);
  }
});

However, Image objects, like <img> tags, require a further GET request to the server to actually load them, so the above probably won't actually work (sorry for the tease). Instead, you'll have to wait for that image to load before calling it, for example:

// Instantiate the image, it's blank here.
var yourImage = new Image();

// Add a callback that uses the fully-loaded img
yourImage.onload = function() {
  new EasyPieChart(element, {
    barColor: function(percent) {
      var ctx = this.renderer.ctx();
      var canvas = this.renderer.canvas();
      return ctx.drawImage(yourImage);
    }
  });
};

// Set the src, that queues it for the actual GET request.
yourImage.src = "path-to-your-img.jpg";