andreich
andreich

Reputation: 1250

How to draw circle with alpha gradient on canvas?

How to draw on canvas like this pic with alpha gradient?
enter image description here

Upvotes: 1

Views: 1029

Answers (1)

Simon Sarris
Simon Sarris

Reputation: 63812

Please specify next time whether you mean the android app canvas or HTML5 canvas on android browsers. If its the former, use . This solution is in JS since its easier to show, and will work fine on either platform.

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:

enter image description here

Now imagine a circle cutting through:

enter image description here

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.net/simonsarris/Msdkv/

Code below:

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

Upvotes: 6

Related Questions