Question

I'm trying to create a "Pie chart" with canvas object but I'd like to fill each slice with an image instead of with colours. Do you think that is possible? I tried to use also "createPattern" but it doesn't work as well. Any suggestions?

Here you can find some code that I've done but it is working filling the slices with colours.

        var color = ["#ccc", "#222", "#fff", "#a61712", "#e42f13", "#2b6637", "#f9d90d", "#f4973a", "#002fba", "#800501"];
        var data = [10, 5, 28, 2, 20, 10, 5, 5, 10, 5];

        function getTotal(){
            var total = 0;
            for (var j = 0; j < data.length; j++) {
                total += (typeof data[j] == 'number') ? data[j] : 0;
            }
            return total;
        }

        function plotData() {
            var canvas;
            var ctx;
            var lastend = 0;
            var total = getTotal();

            canvas = document.getElementById("canvas");
            ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            for (var i = 0; i < data.length; i++) {
                ctx.fillStyle = color[i];
                ctx.beginPath();
                ctx.moveTo(200,150);
                ctx.arc(200, 150, 150, lastend,lastend+(Math.PI*2*(data[i]/total)),false);
                ctx.lineTo(200,150);
                ctx.strokeStyle = "#000";
                ctx.lineWidth = 5;
                ctx.stroke();
                ctx.fill();
                lastend += Math.PI*2*(data[i]/total);
            }
        }

        plotData();
Était-ce utile?

La solution

You have several options to fill your wedge with an image or pattern.

For either option you must do ctx.closePath so your image/pattern stay within the bounds of the wedge.

You should have more success with fill pattern after you do closePath. :-)

Alternatively, set a clipping region created by your wedge:

  • Save the unclipped context state: ctx.save();
  • Create your wedge path.
  • do ctx.clip() and all new drawings will only be drawn inside your wedge
  • drawImage your image or patterned fill ( with clip, the image will be restricted to the wedge)
  • Restore the unclipped context state: ctx.restore();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top