最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Circle(ARC) gradient fill with canvas JS - Stack Overflow

programmeradmin4浏览0评论

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 must be dynamic.

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

But with JS..

Thanks.

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 must be dynamic.

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

But with JS..

Thanks.

Share Improve this question edited May 23, 2017 at 12:32 CommunityBot 11 silver badge asked Apr 16, 2013 at 20:59 user2288183user2288183 1212 silver badges12 bronze badges 1
  • Not enough info to even start helping! – markE Commented Apr 17, 2013 at 2:49
Add a ment  | 

1 Answer 1

Reset to default 16

Great question. Gradients along paths in canvas are hard. The easiest way is to fudge it.

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, going from green to gray, top to bottom.
  • The other on the right side, going from white to gray, top to bottom.

Imagine a square made of those two gradients:

Now imagine a circle cutting through:

That's all you gotta do.

To "cut" through like that its easiest to use clipping regions, so I've made an example doing that.

Here's the live example: http://jsfiddle/simonsarris/Msdkv/

Code below! Hope that 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
发布评论

评论列表(0)

  1. 暂无评论