Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw arc will linear gradient html5 canvas

Tags:

html

canvas

I have a circular arc drawn in canvas is it possible to give it linear gradient with three colors??

like image 953
wilsonrufus Avatar asked Jan 07 '13 10:01

wilsonrufus


1 Answers

Yes, it's possible! There is a method in Javascript, named createLinearGradient which gets as source the canvas context and applies a gradient defined by sx, sy, dx, dy coordinates. The first two options defines the starting coordinates and last two the ending coordinates.

var gradient = context.createLinearGradient(sx, sy, dx, dy);

After invoking this method you can apply gradient colors to your canvas by calling the colorStop method:

gradient.addColorStop(0,   '#f00'); // red
gradient.addColorStop(0.5, '#ff0'); // yellow
gradient.addColorStop(1,   '#00f'); // blue

These are the basic ingredients for implementing a gradient on a canvas. The next step would be to calculate the circular color gradient positions if you need a circular gradient. This can be satisfied by the following formula:

var applyAngle = function (point, angle, distance) {
    return {
          x : point.x + (Math.cos(angle) * distance),
          y : point.y + (Math.sin(angle) * distance)
    };
};

Then plugin the resulted x and y position into the createLinearGradient method, which would create a nice looking circular gradient. Of course you need to use the arc method to make it circular.

like image 99
Endre Simo Avatar answered Sep 22 '22 17:09

Endre Simo