Circle Gradient Fill (ARC) with JS Canvas

I need to draw a dynamic donut chart - something similar to -

http://194.90.28.56/~dev1/t.jpg 

The green part indicates the percentage (in this case, 27%) - it should be dynamic.

I think I need to do something like Android - How to draw a gradient based on an arc

But with JS ..

Thanks.

+4
source share
1 answer

Great question. The gradients along the tracks on the canvas are complex. The easiest way is to wash yourself.

Instead of thinking of your image as a gradient that follows a circular path, think of it as two linear gradients.

  • One on the left side, from green to gray, from top to bottom.
  • The other is on the right side, from white to gray, from top to bottom.

Imagine a square of these two gradients:

enter image description here

Now imagine a circle cutting through:

enter image description here

What you have to do.

To "cut", as it was the easiest way, use clipping areas, so I made an example of this.

Here is a live example: http://jsfiddle.net/simonsarris/Msdkv/

The code is below! Hope this helps.

 var greenPart = ctx.createLinearGradient(0,0,0,100); greenPart.addColorStop(0, 'palegreen'); greenPart.addColorStop(1, 'lightgray'); var whitePart = ctx.createLinearGradient(0,0,0,100); whitePart.addColorStop(0, 'white'); whitePart.addColorStop(1, 'lightgray'); var width = 20; ctx.lineWidth = width; // First we make a clipping region for the left half ctx.save(); ctx.beginPath(); ctx.rect(-width, -width, 50+width, 100 + width*2); ctx.clip(); // Then we draw the left half ctx.strokeStyle = greenPart; ctx.beginPath(); ctx.arc(50,50,50,0,Math.PI*2, false); ctx.stroke(); ctx.restore(); // restore clipping region to default // Then we make a clipping region for the right half ctx.save(); ctx.beginPath(); ctx.rect(50, -width, 50+width, 100 + width*2); ctx.clip(); // Then we draw the right half ctx.strokeStyle = whitePart; ctx.beginPath(); ctx.arc(50,50,50,0,Math.PI*2, false); ctx.stroke(); ctx.restore(); // restore clipping region to default 
+13
source

All Articles