0

I am building an app in Rails, and I am using a gem called easy_as_pie which enables me to use this Jquery plugin called 'Easy Pie Chart' (http://rendro.github.io/easy-pie-chart/)

I have the pie chart working no problem, using the following code:

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

The question I have, is whether not it would be possible to have the chart load a background image instead of a solid colour. In the documentation it allows you to use a gradient with a function, using the following code:

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

I was hoping to get the gradient working, then work on trying to manipulate the function to load in an image. But I have been unsuccessful in even getting the gradient to work.

abbott567
  • 862
  • 6
  • 18

1 Answers1

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";
Adam Kewley
  • 1,224
  • 7
  • 16
  • Hi Adam, thanks for taking the time to reply. Unfortunately, I couldn't get the gradient working. I tried dropping the barColor function directly into where the `barColor: "white"` was in the working example, but it throws a load of errors in the console. Is it clear to you how to integrate the gradient example into the working one? I can't figure that part out. Thanks – abbott567 May 04 '15 at 19:38