[Chartjs]-Chart.js Pie Chart: How to set background image for segment

1👍

Subclass Pie, rewrite the initializer and addData – in the initializer re-define draw, adding one line:

if(this.bg_img)ctx.fillStyle=ctx.createPattern(this.bg_img,"repeat");  

, right after it says:

ctx.fillStyle = this.fillColor;

(copy Pie’s draw, add that line – or just copy my AltPie subclass from the bottom of the attached fiddle) This could be different for later versions but that’s how Chart.js 1.01 is.

Also in your Pie subclass you will add a property (for example call it bg_img) for sending the background image through. To do this there is a one-line addition, so re-define addData inside AltPie and add the property inside the splice line:

bg_img : segment.bg_img,

for example somewhere around the line

fillColor : segment.color,  

That’s most of it – other than that you will load and then attach the images to the data you’re making the chart with. To load them you can use

....img=new Image();...img.src=...and - img.onload=function()(..recurse-load-next,  

with a recursing callback similar to solution #2 from this page:
stackoverflow.com/questions/4960111/image-as-a-background-to-a-drawn-shape
I think you would need to make sure the images are done loading before attaching them to the data and sending them through to the Chart.js renderer, hence the recursion pattern to load them one by one before attaching them to the chart data and then creating the new AltPie chart.

The end result is that your images will show up in the pie pieces backgrounds or you can still use a color background if there’s no image. It changes the html5 canvas ink pattern

(ctx.fillStyle=ctx.createPattern(this.bg_img,"repeat"))

to be the image you attached to the chart data, also taken from solution #2 from the same page: stackoverflow.com/questions/4960111/image-as-a-background-to-a-drawn-shape.

For the complete working example see attached fiddle https://jsfiddle.net/arlon_arriola/pkwftkp2/

The dependencies for loading the page are Chart.js file (v1.01?) (which is just copy/pasted into the fiddle at the top making the code look extremely long but the relvant code is at the very bottom), and the images inside your ./imgs/patterns/ folder, and the reference to some hosted jquery (1.9?). (and a body tag)

I am sure you could get image rollovers too, just attach two images to the data, figure out where it re-draws for hovering and modify it the same way as the regular draw.

Leave a comment