问题描述
我有一个在画布上绘制的圆弧可以给它三种颜色的线性渐变
I have a circular arc drawn in canvas is it possible to give it linear gradient with three colors??
像这个例子
推荐答案
是的,这是可能的!在JavaScript中有一个名为 createLinearGradient
的方法,它作为画布上下文的源,并应用由 sx
定义的渐变, sy
, dx
, dy
前两个选项定义起始坐标,最后两个选项定义结束坐标。
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);
调用此方法后,您可以通过调用 colorStop
方法:
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 base ingredients for implementing a gradient on a canvas. Then, 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)
};
};
然后插入结果 x
c $ c> y 定位到createLinearGradient方法中,这将创建一个漂亮的圆形渐变。当然,您需要使用 arc
方法使其循环。
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.
这篇关于绘制弧线性渐变html5画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!