我正在尝试使用渐变填充画布的某个区域,但我想能够设置渐变的角度。
我知道可以通过在创建渐变时使用不同的值(ctx.createLinearGradient(x1, y1, x2, y2)
)来实现,就像这里所示:
但我似乎无法理解需要将角度(弧度)转换为产生相同角度的渐变大小所需的数学公式(我所指的角度是垂直于渐变方向的角度,因此0弧度的角度会显示在右侧的渐变)
简而言之,如何将弧度数量转换为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();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="test" width="500" height="500"></canvas>
(这样没人会浪费时间:我特意不想在这种情况下使用 context.rotate()
)