I have a circular arc drawn in canvas is it possible to give it linear gradient with three colors??
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With