我尝试使用渐变来填充画布的一个区域,但我希望能够设置渐变的Angular 。
我知道这是可能的,通过在创建梯度(ctx.createLinearGradient(x1, y1, x2, y2)
)时使用不同的值,如下所示:
的数据
但我似乎无法理解将Angular (弧度)转换为梯度大小所需的数学运算,从而产生相同的Angular (我所指的Angular 与梯度方向垂直,因此0弧度Angular 将显示右侧的梯度)
简而言之,我如何将(数量)弧度转换为X乘Y形状?
$(document).ready(function(){
var canvas = document.getElementById("test");
var ctx = canvas.getContext("2d");
var angle = 0.5;
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.arc(100, 100, 100, 0, -angle, true);
ctx.lineTo(100, 100);
ctx.closePath();
// Convert angle into coordinates to tilt the grad
// grad should be perpendicular to the top edge of the arc
var grad = ctx.createLinearGradient(0, 0, 0, 100);
grad.addColorStop(0, "rgba(0,0,0,0)");
grad.addColorStop(1, "rgba(0,0,0,0.8)");
ctx.fillStyle = grad;
ctx.fill();
})
个字符
(So没有人会浪费时间:我特别不想在这种情况下使用context.rotate()
)
1条答案
按热度按时间jhiyze9q1#
你可以使用cos和sin的Angular 来定义给出梯度的直线。剩下的唯一事情就是给出长度:
字符串
渐变将沿沿着(垂直)给定的线渲染。
没有说明,但是如果你需要根据Angular 和盒子来计算线的长度,你可以使用law of sines来完成(以这种方式使用)。下面的例子使用固定的半径。你也可以通过计算
length = Math.sqrt(diffX*diffX + diffY*diffY);
来使用(x1,x2)的最大长度。示例
的数据